3
votes

I'm trying to use bitwise_and in order to exclude all the rest of an image based on a threshold, but when I try it gives:

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') in binary_op, file /home/schirrel/Github/opencv/opencv-2.4.10/modules/core/src/arithm.cpp, line 1021 terminate called after throwing an instance of 'cv::Exception' what(): /home/schirrel/Github/opencv/opencv-2.4.10/modules/core/src/arithm.cpp:1021: error: (-209) The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array' in function binary_op

My code is

Mat src, src_gray, dst;

int main()
{
    src = imread("robosoccer.jpg", 1);
    cvtColor(src, src_gray, CV_BGR2GRAY);
    threshold(src_gray, dst, 150, 255, 1);
    Mat res;
    bitwise_and(src, dst, res);
    imshow("AND", res);
    ("hold", res);
    waitKey(0);
    return (0);
}

Can you help me?

2

2 Answers

5
votes

You should use:

bitwise_and(src_gray, dst, res);

The error means that the two images src and dst dimensions are not equal, since they differ in the number of channels.

You can also write:

Mat res = src_gray & dst;

or:

Mat res = src_gray.clone();
res.setTo(Scalar(0), ~dst);

If you need the color image, you can do like @sturkmen suggested

bitwise_and( src, src, res, dst );

or:

Mat res = src.clone();
res.setTo( Scalar( 0, 0, 0 ), ~dst);
0
votes

Most errors associated with binary_op when using openCV when syntax looks correct might be as a result of inconsistent dimensions used when working with example syntax bellow.

imgInv = cv2.cvtColor() 
img = cv2.bitwise_and()
img = cv2.bitwise_or()

you can resize image with syntax below after a cam capture or video/image load ||Where width and height is the resolution size you want to use|| eg HD(720, 480)

cap = cv2.VideoCapture(0)
cap.set(3, width)
cap.set(4, height)

while True:  
     success, img = cap.read()
     img = cv2.resize(img, (width, height))