OpenCV笔记4-图像操作

1 读写图像

  • imread:可以指定加载为灰度或者RGB图像
  • imwrite:保存图像文件,类型由扩展名决定

2 读写像素

  • at(int y, int x)方法
    y表示行号、x表示列号。at是一个模板方法,使用时需要指定返回值的预期类型,如image.at<uchar>(j, i) = 255;
  • 读一个GRAY像素点的像素值(CV_8UC1)
//方法1
Scalar intensity = img.at<Vec3b>(y, x);
//Vec3b是一种数据类型,表示3通道无符号类型的向量
//y表示行号,x表示列号
//方法2
Scalar intensity = img.at<uchar>(Point(x, y));
  • 读一个BGR像素点的像素值
Vec3f intensity = img.at<Vec3b>(y, x);	
float blue  = intensity.val[0];		//取B分量
float green = intensity.val[1];		//取G分量
float red   = intensity.val[2];		//取R分量

3 修改像素值

  • 灰度图像
img.at<uchar>(y, x) = 128;
  • RGB三通道图像
img.at<Vec3b>(y, x)[0] = 128;	//blue
img.at<Vec3b>(y, x)[1] = 128;	//green
img.at<Vec3b>(y, x)[2] = 128;	//red
  • 空白图像赋值
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);

在这里插入图片描述

  • 彩色图像反差
//方法1
	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];		//三通道中的顺序为BGR
				int r = src.at<Vec3b>(row, col)[2];
				dst.at<Vec3b>(row, col)[0] = 255 - b;	//取反操作,并把最终结果存到dst中
				dst.at<Vec3b>(row, col)[1] = 255 - g;
				dst.at<Vec3b>(row, col)[2] = 255 - r;
			}
		}
	}

//方法2
	bitwise_not(src, dst);			//图像反差函数,等于上述代码,位操作
	imshow("RGB invert", dst);

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/CC_monster/article/details/86656726
今日推荐