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

    科技2022-07-12  109

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

    #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; }

    Processed: 0.010, SQL: 8