其实按理说这并不是一件困难的工作,但是由于种种原因,在OpenCV中读取的黑白图像并不是我们想像的只有一个通道,而是3通道的。但是当我们使用Mat image = imread("D:/picture/images/baboon2.jpg",0);之后,不论是彩色图像还是黑白图像都会转换为单通道。明白了这个之后,我们的程序就简单了:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
int main()
{
//Mat image = imread("D:/picture/images/baboon2.jpg",0);
//Mat image = imread("D:/picture/images/baboon2.jpg");
//Mat image = imread("D:/picture/images/binary.bmp");
Mat image = imread("D:/picture/image.png");
if(!image.data)
return -1;
int row = image.rows;
int col = image.cols;
int cnt= 0;
for(int i = 0; i < row;i++)
{
for(int j = 0; j<col;j++)
{
if(image.channels() ==3)
{
if( (int)(image.at<Vec3b>(i,j)[0]) != 0 && (int)(image.at<Vec3b>(i,j)[0]) != 255 &&
(int)(image.at<Vec3b>(i,j)[1]) != 0 && (int)(image.at<Vec3b>(i,j)[1]) != 255 &&
(int)(image.at<Vec3b>(i,j)[2]) != 0 && (int)(image.at<Vec3b>(i,j)[2]) != 255)
{
cnt++;
}
}
else if(image.channels() ==1)
{
if((int)(image.at<uchar>(i,j)) != 0 && (int)(image.at<uchar>(i,j)) != 255)
{
cnt++;
}
}
}
}
if(cnt == 0)
{
std::cout<<"这是黑白图像"<<std::endl;
}
else
{
std::cout<<"这是不是黑白图像"<<std::endl;
}
//显示图像以验证结果
imshow("图像",image);
waitKey(0);
return 0;
}