In fact, this is not a difficult task, but for various reasons, the black and white images read in opencv are not just one channel as we imagined, but three channels. However, when we use mat image = imread ("D:/picture/images/baboon2.jpg", 0), both color and black images are converted to single channels. After understanding this, our program will be simple:
# Include <opencv2/CORE/core. HPP> # include <opencv2/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 <"this is a black-and-white image" <STD: Endl ;} else {STD: cout <"This is not a black-and-white image" <STD: Endl;} // display the image to verify the result imshow ("image", image ); waitkey (0); Return 0 ;}
You only need to determine whether each pixel value is 0 or 255. If not, it is not a black-and-white image.