Opencv中彩色图像转灰度及多张图片显示

该博客主要介绍了如何使用OpenCV库进行彩色图像到灰度图像的转换,并在灰度图像中通过比较像素值实现边缘检测。作者通过比较像素间的差异来识别边界点,并将这些边界点在原始彩色图像中标记为绿色。最后,展示了如何同时显示原始图像和灰度图像。
摘要由CSDN通过智能技术生成

主要熟悉图片中获取灰度图像的像素值、彩色图片像素的获取;多张图片的同时显示。(边缘检测与上一篇原理一致:周边像素存在较大差异即为边缘像素。但是是在灰度图像中确定边缘像素的位置,再在原始图像中将边缘像素的颜色改为绿色)

#include<opencv2\opencv.hpp>
#include<vector>
#include<iostream>
using namespace std;
using namespace cv;
int main()
{
	Mat image0, imgGray;
	image0 = imread("D:\\1.jpg");

	//彩色图像转灰色图像
	cvtColor(image0, imgGray, CV_BGR2GRAY);

	int row = imgGray.rows;
	int col = imgGray.cols;
	
	struct Label
	{
		int row;
		int column;

	};

	vector<Label> Boundary;
	Label temp;

	double thres = 20;
	
	for (int i = 2; i <= imgGray.rows - 2; i++)
	{
		//获取第i-1  i  i+1行的地址
		uchar *data1 = imgGray.ptr<uchar>(i-1);
		uchar *data2 = imgGray.ptr<uchar>(i);
		uchar *data3 = imgGray.ptr<uchar>(i+1);
		for (int j = 2; j < imgGray.cols - 2; j++)
		{
			int I1 = data1[j - 1];
			int I2 = data1[j];
			int I3 = data1[j + 1];

			int I4 = data2[j - 1];
			int I5 = data2[j];
			int I6 = data2[j + 1];

			int I7 = data3[j - 1];
			int I8 = data3[j];
			int I9 = data3[j + 1];

			bool judge01 = (abs(I5 - I1) >= thres);
			bool judge02 = (abs(I5 - I2) >= thres);
			bool judge03 = (abs(I5 - I3) >= thres );
			bool judge04 = (abs(I5 - I4) >= thres );
			bool judge05 = (abs(I5 - I6) >= thres);
			bool judge06 = (abs(I5 - I7) >= thres );
			bool judge07 = (abs(I5 - I8) >= thres );
			bool judge08 = (abs(I5 - I9) >= thres );

			//只要其中有个不对,则直接为边界点
			bool last = (judge01 == 1 || judge02 == 1 || judge03 == 1 || judge04 == 1 || judge05 == 1 || judge06 == 1 || judge07 == 1 || judge08 == 1);
			if (last)
			{
				temp.row = i;
				temp.column = j;
				Boundary.push_back(temp);
			}
		}
	}

	//将原来彩色图像边缘进行显示
	for (int i = 0; i < Boundary.size(); i++)
	{
		int row = Boundary[i].row;
		int column = Boundary[i].column;

		//设置成绿色
		image0.ptr<uchar>(row)[column * 3] = 0;
		image0.ptr<uchar>(row)[column * 3 + 1] = 255;
		image0.ptr<uchar>(row)[column * 3 + 2] = 0;
	}
	//多张图片同时显示
	namedWindow("image0", WINDOW_NORMAL);
	imshow("image0", image0);

	namedWindow("imggrey", WINDOW_NORMAL);
	imshow("imggrey", imgGray);
	waitKey();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

点云实验室lab

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值