如何区别一幅图像是否是黑白图像

这篇文章的思路是很清晰的,但是个人觉得这样判断太耗时,在实际做工程的时候完全可以多判断一些样本点来节约时间


其实按理说这并不是一件困难的工作,但是由于种种原因,在OpenCV中读取的黑白图像并不是我们想像的只有一个通道,而是3通道的。但是当我们使用Mat image = imread("D:/picture/images/baboon2.jpg",0);之后,不论是彩色图像还是黑白图像都会转换为单通道。明白了这个之后,我们的程序就简单了:

[cpp]  view plain copy
  1. #include <opencv2/core/core.hpp>  
  2. #include <opencv2/highgui/highgui.hpp>  
  3. #include <iostream>  
  4. using namespace cv;  
  5. int main()  
  6. {  
  7.     //Mat image = imread("D:/picture/images/baboon2.jpg",0);  
  8.     //Mat image = imread("D:/picture/images/baboon2.jpg");  
  9.     //Mat image = imread("D:/picture/images/binary.bmp");  
  10.     Mat image = imread("D:/picture/image.png");  
  11.   
  12.   
  13.     if(!image.data)  
  14.         return -1;  
  15.       
  16.     int row = image.rows;  
  17.     int col = image.cols;  
  18.     int cnt= 0;  
  19.     for(int i = 0; i < row;i++)  
  20.     {  
  21.         for(int j = 0; j<col;j++)  
  22.         {  
  23.             if(image.channels() ==3)  
  24.             {  
  25.   
  26.                   
  27.                 if( (int)(image.at<Vec3b>(i,j)[0]) != 0 &&  (int)(image.at<Vec3b>(i,j)[0]) != 255 &&   
  28.                     (int)(image.at<Vec3b>(i,j)[1]) != 0 &&  (int)(image.at<Vec3b>(i,j)[1]) != 255 &&   
  29.                     (int)(image.at<Vec3b>(i,j)[2]) != 0 &&  (int)(image.at<Vec3b>(i,j)[2]) != 255)  
  30.                 {  
  31.                     cnt++;  
  32.                 }  
  33.                   
  34.             }  
  35.             else if(image.channels() ==1)  
  36.             {  
  37.                 if((int)(image.at<uchar>(i,j)) != 0 &&  (int)(image.at<uchar>(i,j)) != 255)  
  38.                 {  
  39.                     cnt++;  
  40.                 }  
  41.             }  
  42.         }  
  43.     }  
  44.     if(cnt == 0)  
  45.     {  
  46.         std::cout<<"这是黑白图像"<<std::endl;  
  47.     }  
  48.     else  
  49.     {  
  50.         std::cout<<"这是不是黑白图像"<<std::endl;  
  51.     }  
  52.       
  53.     //显示图像以验证结果  
  54.     imshow("图像",image);  
  55.     waitKey(0);  
  56.     return 0;  
  57. }  


只需要判断每个像素值是否为0或者255就行了,如果都不是,那么就不是黑白图像。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值