Search code examples
c++opencvmatbitwise-and

OpenCV inRange changes Mat type


I can't get rid of this error in OpenCV:

OpenCV Error: Sizes of input arguments do not match (The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array')

I found out with Mat.type(); that all of my Mat(img) has type 16 but after function inRange my img3 changed type to 0. Then I can't use function bitwise_and because it has not the same type.

How can I convert it to same type?

Mat img1 = imread(argv[1], 1);
Mat img2, img3, img4;

cvtColor(img1, img2, CV_BGR2HSV);
GaussianBlur(img2, img2, Size(15,15), 0); 
inRange(img2, Scalar(h_min_min,s_min_min,v_min_min), Scalar(h_max_min,s_max_min,v_max_min), img3); // now img3 changed type to 0
bitwise_and(img1, img3, img4); // img1.type()=16, img3.type()=0 ERROR

Solution

  • This is normal, as inRange returns a 1-channel mask (a value for each pixel), so to perform the bitwise operation simply transform the mask back to 3-channel image:

    cvtColor(img3,img3,CV_GRAY2BGR);
    bitwise_and(img1, img3, img4);// now both images are CV_8UC3 (=16)
    

    EDIT: as Berak says, to change the number of channels you must use cvtColor, not Mat::convertTo. Sorry about that.