openCV学习笔记(三)-- 图像操作

1.像素操作
openCV学习笔记(三)-- 图像操作_第1张图片

openCV学习笔记(三)-- 图像操作_第2张图片

修改单/多通道像素值—取反操作

Mat dst;
dst.create(src.size(), src.type());
int height = src_gray.rows;
int width = src_gray.cols;
int nc = src.channels();



for (int row = 0; row < height; row++)
{
	for (int col = 0; col < width; col++)
	{
		//转换为灰度图像后,变成单通道
		if (nc==1)
		{
			int gray = src_gray.at<uchar>(row, col);//获取对应行,列的像素值
			src_gray.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对象
			dst.at<Vec3b>(row, col)[1] = 255 - g;
			dst.at<Vec3b>(row, col)[2] = 255 - r;
		}
		
	}
}

bitwise_not(src, dst);//相当于前面for循环的东西,像素反色操作,按位取反

2.线性混合
openCV学习笔记(三)-- 图像操作_第3张图片
openCV学习笔记(三)-- 图像操作_第4张图片

代码:

//-----图像混合
Mat src1, src2, dst;
	src1 = imread("C:/Users/18929/Desktop/博客项目/项目图片/01.jpg");
	src2 = imread("C:/Users/18929/Desktop/博客项目/项目图片/02.jpg");
	if (src1.empty())
	{
		printf("could not load src1!");
		return -1;
	}
	if (src2.empty())
	{
		printf("could not load src2!");
		return -1;
	}
	double alpha = 0.5;
	if (src1.rows == src2.rows && src1.cols == src2.cols && src1.type() == src2.type())
	{
		addWeighted(src1, alpha, src2, (1.0 - alpha), 0.0, dst);//图像混合公式
		namedWindow("blend_demo", WINDOW_AUTOSIZE);
		imshow("blend_demo", dst);
	}
	else
	{
		printf("could not blend images.the size of images or the type of images is not same");
	}

3.修改图片的对比度和亮度

修改对比度及亮度公式:
g(i,j) = a*f(i,j) + b; // a>0,b为增益变量,a调整对比度,b调整亮度

//修改图片对比度和亮度
	int height = src.rows;
	int width = src.cols;
	dst = Mat::zeros(src.size(), src.type());
	float alpha = 1.5;
	float beta = 10;
	for (int row = 0; row < height; row++)
	{
		for (int col = 0; col < width; col++) {
			if (src.channels() == 3)
			{
				float b = src.at<Vec3b>(row, col)[0];
				float g = src.at<Vec3b>(row, col)[1];
				float r = src.at<Vec3b>(row, col)[2];

				dst.at<Vec3b>(row, col)[0] = saturate_cast<uchar>(b * alpha + beta);//修改亮度,对比度公式,alpht---对比度,beta----亮度
				dst.at<Vec3b>(row, col)[1] = saturate_cast<uchar>(g * alpha + beta);
				dst.at<Vec3b>(row, col)[2] = saturate_cast<uchar>(r * alpha + beta);

			}
			else if (src.channels() == 1) {
				float v = src.at<uchar>(row, col);
				dst.at<uchar>(row, col) = saturate_cast<uchar>(v * alpha + beta);
			}
		}
	}

你可能感兴趣的:(openCV)