OpenCV--影象的反色與灰度圖顯示
阿新 • • 發佈:2018-12-30
對於單通道影象:
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;row<rows;row++){
for(int col = 0;col<cols;col++){
dest.at<uchar>(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;row<rows;row++){
for(int col=0;col<cols;col++){
int b = src.at<Vec3b>(row,col)[0];
int g = src.at<Vec3b>(row,col)[1];
int r = src.at<Vec3b>(row,col)[2];
dest.at<Vec3b>(row,col)[0] = 255-b;
dest.at<Vec3b>(row,col)[1] = 255-g;
dest.at<Vec3b>(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;row<rows;row++){
for(int col=0;col<cols;col++){
int b = src.at<Vec3b>(row,col)[0];
int g = src.at<Vec3b>(row,col)[1];
int r = src.at<Vec3b>(row,col)[2];
dest.at<uchar>(row,col) = max(r,max(g,b));//選擇bgr中最大值
//dest.at<uchar>(row,col) = min(r,min(g,b));//選擇bgr中最小值
}
}
namedWindow("min,灰度圖",CV_WINDOW_AUTOSIZE);
imshow("min,灰度圖",dest);
cvWaitKey();
}