1
votes

I have the code on python in which I open an image and set mask on it:

import cv2
    import numpy as np
    
    img1 = np.zeros((250, 500, 3), np.uint8)
    img1 = cv2.rectangle(img1,(200, 0), (300, 100), (255, 255, 255), -1)
    img2 = cv2.imread("blackie.jpg")
    
    bitAnd = cv2.bitwise_and(img2, img1)
    bitOr = cv2.bitwise_or(img2, img1)
    bitXor = cv2.bitwise_xor(img1, img2)
    bitNot1 = cv2.bitwise_not(img1)
    bitNot2 = cv2.bitwise_not(img2)
    
    cv2.imshow("img1", img1)
    cv2.imshow("img2", img2)
    cv2.imshow('bitAnd', bitAnd)
    cv2.imshow('bitOr', bitOr)
    cv2.imshow('bitXor', bitXor)
    cv2.imshow('bitNot1', bitNot1)
    cv2.imshow('bitNot2', bitNot2)
    
    cv2.waitKey(0)
    cv2.destroyAllWindows()

That gives me the error when I try to bitwise an image:

error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-ttbyx0jz\opencv\modules\core\src\arithm.cpp:214: error: (-209: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 function 'cv::binary_op'
1
make sure that img1 and img2 have the same shapes - crackanddie
“Sizes of input arguments do not match” is pretty clear. - Cris Luengo

1 Answers

1
votes

@crackanddie is right you can use the following code :

import cv2
import numpy as np
import sys

img2 = cv2.imread("blackie.jpg")
img1 = np.zeros(img2.shape, np.uint8)

if img2.shape[0] > 200 or img2.shape[1] > 300:
    print("Bounding box is bigger then target image")
    sys.exit(0)

img1 = cv2.rectangle(img1,(200, 0), (300, 100), (255, 255, 255), -1)

bitAnd = cv2.bitwise_and(img2, img1)
bitOr = cv2.bitwise_or(img2, img1)
bitXor = cv2.bitwise_xor(img1, img2)
bitNot1 = cv2.bitwise_not(img1)
bitNot2 = cv2.bitwise_not(img2)

cv2.imshow("img1", img1)
cv2.imshow("img2", img2)
cv2.imshow('bitAnd', bitAnd)
cv2.imshow('bitOr', bitOr)
cv2.imshow('bitXor', bitXor)
cv2.imshow('bitNot1', bitNot1)
cv2.imshow('bitNot2', bitNot2)

cv2.waitKey(0)
cv2.destroyAllWindows()