Ask Your Question

Revision history [back]

Issues with bitwise analysis of two Mat

I am writing a script to compare two thresholded images and obtain the percentages of each logical instance for the following table.

image description

The two images are corresponding to a laminate sample that was split in half. So I flip one of the images in order to accommodate for the pixel-by-pixel operations. In order to obtain the percentages I am using bitwise NOR, XOR and AND - then I count the number of non zero pixels for each instance. My issue is that the resulting percentage is always greater than 100.

I would greatly appreciate it if someone can lead me in the right direction. I have re-written this script several times with other functions like compare() and it gives me the same results. I must be missing something quite simple.

My code is shown below:

int main(int argc, char** argv ){

    Mat imgleft_original = imread("img_side_a.JPG");
Mat imgright_original = imread("img_side_b.JPG");
Mat flipped, imgleft_thresh;
flip(imgright_original, flipped, 1);
cvtColor(imgleft_original,imgleft_thresh,CV_BGR2GRAY);
cvtColor(flipped,flipped,CV_BGR2GRAY);
threshold(flipped,flipped,0,255,CV_THRESH_OTSU);
threshold(imgleft_thresh,imgleft_thresh,0,255,CV_THRESH_OTSU);

    imshow("Original Left", imgleft_original);
imshow("Original Right", imgright_original);
imshow("thresh Left", imgleft_thresh);
imshow("thresh Right", flipped);

Mat ImgOR, ImgAND, ImgXOR, ImgNOR;

resize(imgleft_thresh, imgleft_thresh, Size(200,600),0,0);
resize(flipped,flipped, Size(200,600),0,0);

bitwise_and(imgleft_thresh,flipped,ImgAND);
bitwise_xor(imgleft_thresh,flipped,ImgXOR);
bitwise_or(imgleft_thresh,flipped,ImgOR);
bitwise_not(ImgOR, ImgNOR);

unsigned int TOTALPIXELS = imgleft_thresh.rows * imgleft_thresh.cols;
unsigned int AND, NOR, XOR;

unsigned int NOR_Pixel_cnt = countNonZero(ImgNOR);
unsigned int XOR_Pixel_cnt = countNonZero(ImgXOR);
unsigned int AND_Pixel_cnt = countNonZero(ImgAND);

AND = 100 * AND_Pixel_cnt / TOTALPIXELS;
XOR = 100 * XOR_Pixel_cnt / TOTALPIXELS;
NOR = 100 * NOR_Pixel_cnt / TOTALPIXELS;

 cout << "Total number of Pixels: " << TOTALPIXELS << endl << endl;
 cout << "XOR: " << XOR <<"%" << " PixelCount: "<< XOR_Pixel_cnt <<endl;
 cout << "AND: " << AND <<"%" << " PixelCount: "<< AND_Pixel_cnt <<endl;
 cout << "NOR: " << NOR <<"%" << " PixelCount: "<< NOR_Pixel_cnt <<endl; 

 waitKey(0);
 return 0;

}