opencv学习(二)矩阵的掩膜操作

矩阵的掩膜操作——根据掩膜重新计算每个像素的像素值,掩膜mask 也称做kernel

掩膜操作作用——实现图像对比度调整

红色是中心像素I(x,y),从上到下,从左到右对每个像素做同样的处理操作,掩膜操作公式如下:

                                             

以下是代码实现:

int main() {
	Mat src, dst;
	src = imread("C:\\Users\\liuhuimin\\Desktop\\pp.jpg");//imread的图像是RGB
	if (!src.data) {
		printf("cloud not load image");
		return -1;
	}
	imshow("原图",src);

	dst = Mat::zeros(src.size(), src.type());//初始化输出图像矩阵
	int cols = (src.cols-1)*src.channels();//获取图像的列数,注意实际图像是三通道
	int rows = src.rows; //获取图像的行数
	int offsetx = src.channels();
	for (int i = 1; i < (rows - 1); i++) {
		uchar* previous = src.ptr<uchar>(i - 1); //上
		uchar* current = src.ptr<uchar>(i);  //获取当前指针
		uchar* next = src.ptr<uchar>(i + 1);//下
		uchar* output = dst.ptr<uchar>(i);
		for (int j = offsetx; j < cols; j++) {
			output[j] = 5 * current[j] - (previous[j] + next[j] + current[j - offsetx] + current[j + offsetx]);
			
		}
	}
	imshow("掩膜后", dst);
	waitKey(0);
	return 0;
}

前后对比图:

出现了一些不好的小斑点。这是因为这项像素点的值的范围不在0~255之间了。 

解决办法如下:

output[j] = saturate_cast<uchar>(5 * current[j] - (previous[j] + next[j] + current[j - offsetx] + current[j + offsetx]));

调用API来实现:

int main() {
	Mat src, dst;
	src = imread("C:\\Users\\liuhuimin\\Desktop\\pp.jpg");//imread的图像是RGB
	if (!src.data) {
		printf("cloud not load image");
		return -1;
	}
	imshow("原图",src);

	dst = Mat::zeros(src.size(), src.type());//初始化输出图像矩阵
	Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
	filter2D(src, dst, src.depth(), kernel);
	imshow("掩膜后", dst);
	waitKey(0);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/lhm_19960601/article/details/82389418