读写图像
imread()可以指定加载图像为灰度图或者RGB格式imwrite()保存图像文件,类型由扩展名决定读写像素
读写一个GRAY像素点的像素值(CV_8UC1)
gray = gray_img.at<uchar>(row, col);
读取一个RGB图像的像素点的像素值
int b = img.at<Vec3b>(row, col)[0];
int g = img.at<Vec3b>(row, col)[1];
int r = img.at<Vec3b>(row, col)[2];
或者
float b = img.at<Vec3f>(row, col)[0];
float g = img.at<Vec3f>(row, col)[1];
float r = img.at<Vec3f>(row, col)[2];
Mat dst;
dst.at<Vec3b>(row, col)[0] = 255 - b;//反写
dst.at<Vec3b>(row, col)[1] = 255 - g;
dst.at<Vec3b>(row, col)[2] = 255 - r;
修改像素值
灰度图像
img.at<uchar>(y,x) = 200;
RGB三通道图像
int b = img.at<Vec3b>(y,x)[0] = 56;//blue
int g = img.at<Vec3b>(y,x)[1] = 124;//green
int r = img.at<Vec3b>(y,x)[2] = 220;//red
空白图像赋值
img=Scalar(0);
ROI选择
Rect r(10, 10, 100, 100);
Mat smallImg = img(r);
Vec3b与Vec3f
Vec3b对应三通道的顺序是blue、green、red的uchar类型数据
Vec3f对应三通道的float类型数据
把CV_8UC1转换到CV32F1实现如下:
src.convertTo(dst, CV_32F);
#include<iostream>#include<opencv2/opencv.hpp>using namespace cv;using namespace std;int main(){Mat img, gray_img, dst;img = imread("D:\\OpenCV\\images\\4.jpg");if (img.empty()){cout << "image loading failed..." << endl;return -1;}namedWindow("input", WINDOW_AUTOSIZE);imshow("input", img);cvtColor(img, gray_img, COLOR_BGR2GRAY);//imshow("gray_img", gray_img);int height = gray_img.rows;int weight = gray_img.cols;int nc = gray_img.channels();//printf("the channel of this image is %d\n", nc);if (nc == 1)//单通道{for (int row = 0; row < height; row++){for (int col = 0; col < weight; col++){int gray = gray_img.at<uchar>(row, col);gray_img.at<uchar>(row, col) = 255 - gray;}}imshow("output", gray_img);}elseif (nc == 3)//三通道{dst.create(img.size(), img.type());for (int row = 0; row < height; row++) {for (int col = 0; col < weight; col++){int b = img.at<Vec3b>(row, col)[0];//读取三个通道的像素值int g = img.at<Vec3b>(row, col)[1];int r = img.at<Vec3b>(row, col)[2];dst.at<Vec3b>(row, col)[0] = 255 - b;//反射操作dst.at<Vec3b>(row, col)[1] = 255 - g;dst.at<Vec3b>(row, col)[2] = 255 - r;gray_img.at<uchar>(row, col) = min(r, min(g, b));}}imshow("gray_img", gray_img);imshow("dst", dst);//imwrite("D:\\OpenCV\\images\\gray_img.jpg", gray_img);//imwrite("D:\\OpenCV\\images\\dst.jpg", dst);}//bitwise_not(img, dst);waitKey(0);return 0;}
来几张效果图
有点吓人是吧,哈哈哈