对于单通道图像:
void Invert1(){
Mat src,dest;
src = imread("lena.jpg");
if(!src.data){
cout << "图像载入失败" << endl;
return ;
}
namedWindow("原图像",CV_WINDOW_AUTOSIZE);
imshow("原图像",src);
cvtColor(src,dest,COLOR_BGR2GRAY);
int rows = src.rows;
int cols = src.cols;
//单通道图像的反色
for(int row = 0;rowfor(int col = 0;coluchar>(row,col) = 255 - dest.at<uchar>(row,col);
}
}
namedWindow("单通道,反色后",CV_WINDOW_AUTOSIZE);
imshow("单通道,反色后",dest);
cvWaitKey();
}
对于三通道图像:
void Invert2(){
Mat src;
src = imread("lena.jpg");
if(!src.data){
cout << "图像载入失败" << endl;
return ;
}
namedWindow("原图像",CV_WINDOW_AUTOSIZE);
imshow("原图像",src);
int rows = src.rows;
int cols = src.cols;
cout << rows << "\t" << cols << endl;
Mat dest;
dest.create(src.size(),src.type());
for(int row = 0;rowfor(int col=0;colint b = src.at(row,col)[0];
int g = src.at(row,col)[1];
int r = src.at(row,col)[2];
dest.at(row,col)[0] = 255-b;
dest.at(row,col)[1] = 255-g;
dest.at(row,col)[2] = 255-r;
}
}
namedWindow("三通道,反色后",CV_WINDOW_AUTOSIZE);
imshow("三通道,反色后",dest);
cvWaitKey();
}
OpenCV提供的函数bitwise_not(src,dest):
void Invert3(){
Mat src,dest;
src = imread("lena.jpg");
if(!src.data){
cout << "图像载入失败" << endl;
return ;
}
namedWindow("原图像",CV_WINDOW_AUTOSIZE);
imshow("原图像",src);
cv::bitwise_not(src,dest);
namedWindow("反色后",CV_WINDOW_AUTOSIZE);
imshow("反色后",dest);
cvWaitKey();
}
不同于使用cvtColor()函数,我们可以自己对像素操作实现灰度图的显示:
void GrayShow(){
Mat src;
src = imread("lena.jpg");
if(!src.data){
cout << "图像载入失败" << endl;
return ;
}
namedWindow("原图像",CV_WINDOW_AUTOSIZE);
imshow("原图像",src);
int rows = src.rows;
int cols = src.cols;
Mat dest = Mat(src.rows,src.cols,0);
for(int row = 0;rowfor(int col=0;colint b = src.at(row,col)[0];
int g = src.at(row,col)[1];
int r = src.at(row,col)[2];
dest.at(row,col) = max(r,max(g,b));//选择bgr中最大值
//dest.at(row,col) = min(r,min(g,b));//选择bgr中最小值
}
}
namedWindow("min,灰度图",CV_WINDOW_AUTOSIZE);
imshow("min,灰度图",dest);
cvWaitKey();
}