furtunb
furtunb

Reputation: 61

OpenCV Mask Error error: (-215:Assertion failed) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function 'cv::binary_op

I am getting this error:

cv2.error: OpenCV(4.1.2) C:\projects\opencv-python\opencv\modules\core\src\arithm.cpp:245: error: (-215:Assertion failed) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function 'cv::binary_op' 

I've read this post which describes my problem (other questions don't), but I couldn't find my answer from there.

here's my code:

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread("manzara.jpg")
imgOther = cv2.imread("fuzuli.jpg") # shape of this is 559, 419, 3

width, height, channel = img.shape # 768, 1024, 3
roi = img[0:width, 0:height]
imgOtherGray = cv2.cvtColor(imgOther, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(imgOtherGray, 220, 255, cv2.THRESH_BINARY_INV)

antiMask = cv2.bitwise_not(mask)


img_background = cv2.bitwise_and(roi, roi, mask=antiMask) # where error occurs
imgOther_fg = cv2.bitwise_and(roi, roi, mask=mask)

dst = cv2.add(img_background, imgOther_fg)
img[0:width, 0:height] = dst
cv2.imshow("image", img)

Upvotes: 1

Views: 2982

Answers (2)

Pad Brogrammer
Pad Brogrammer

Reputation: 31

I was running into a similar issue, and I believe your issue stems from the Region of Interest (roi) that you're using. In short: You tried selecting a region of interest which contained coordinates which weren't in the original image.

In OpenCV, you define an ROI as follow (assuming you already opened an image called "image")

roi = image[y1:y2,x1:x2]

Here, the coordinate (x1, y1) would relate to the upper left corner of the image, and the coordinate (x2, y2) would be the lower right corner of the image.

In your code, you mixed up the width (x) and height (y), by listing x (the width) first. OpenCV does them the opposite way, with the y-variable (height) first. You should change your roi variable to the following:

roi = img[0:height,0:width]

This will create a region of interest which is the size of your entire image.

Upvotes: 1

furtunb
furtunb

Reputation: 61

I've figured out that I am trying to work with wrong image named "img", img's shape is bigger than imgOther's shape, so it causes a problem. I changed the

width, height, channel = img.shape # 768, 1024, 3
roi = img[0:width, 0:height]

code with

width, height, channel = imgOther.shape # 768, 1024, 3
roi = img[0:width, 0:height]

and my problem is solved

Upvotes: 3

Related Questions