1 读写图像
- imread:可以指定加载为灰度或者RGB图像
- imwrite:保存图像文件,类型由扩展名决定
2 读写像素
at(int y, int x)
方法
y表示行号、x表示列号。at是一个模板方法,使用时需要指定返回值的预期类型,如image.at<uchar>(j, i) = 255;
- 读一个GRAY像素点的像素值(CV_8UC1)
Scalar intensity = img.at<Vec3b>(y, x);
Scalar intensity = img.at<uchar>(Point(x, y));
Vec3f intensity = img.at<Vec3b>(y, x);
float blue = intensity.val[0];
float green = intensity.val[1];
float red = intensity.val[2];
3 修改像素值
img.at<uchar>(y, x) = 128;
img.at<Vec3b>(y, x)[0] = 128;
img.at<Vec3b>(y, x)[1] = 128;
img.at<Vec3b>(y, x)[2] = 128;
img = Scalar(0);
- ROI选择(Region of Interest:感兴趣区域)
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);
4 代码
Mat src, gray_src;
src = imread("D:/C++project/OpenCVProject/Lena.jpg");
if (src.empty()) {
cout << "could not load image ..." << endl;
return -1;
}
namedWindow("input",WINDOW_AUTOSIZE);
imshow("input", src);
- 反差图像
反差图像就是用原图像素所能表达的最大像素值减去原图像素值之后所形成的图像。由于本程序采用的是Vec3b和uchar类型的图像,所以每通道的最大值为255,255 - 原值 = 反差值。
cvtColor(src, gray_src, COLOR_BGR2GRAY);
namedWindow("output", WINDOW_AUTOSIZE);
imshow("output", gray_src);
int height = gray_src.rows;
int width = gray_src.cols;
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
int gray = gray_src.at<uchar>(row, col);
gray_src.at<uchar>(row, col) = 255 - gray;
}
}
imshow("gray invert", gray_src);
Mat dst;
dst.create(src.size(), src.type());
int height_dst = src.rows;
int width_dst = src.cols;
int nc = src.channels();
for (int row = 0; row < height_dst; row++) {
for (int col = 0; col < width_dst; col++) {
if (nc == 1) {
int gray = gray_src.at<uchar>(row, col);
gray_src.at<uchar>(row, col) = 255 - gray;
}
else if (nc == 3) {
int b = src.at<Vec3b>(row, col)[0];
int g = src.at<Vec3b>(row, col)[1];
int r = src.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;
}
}
}
bitwise_not(src, dst);
imshow("RGB invert", dst);