在函数 'cv::binary_op' 中,屏蔽图像时 openCV 出错

时间:2021-04-12 17:38:40

标签: python opencv opencv-python

我在 stackoverflow 上使用了一个代码来屏蔽我变成蒙版的图像,但是当我想在第 31 行应用它时,我收到了我一生中从未见过的错误。

这里是错误

File "main.py", line 31, in <module>
    masked = cv2.bitwise_and(img_to_mask,img_to_mask,mask = img_mask)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-6sxsq0tp\opencv\modules\core\src\arithm.cpp:250: error: (-215:Assertion failed) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function 'cv::binary_op'

我的代码:

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

print("Loaded libs.")

img = cv2.imread('test.png')

img = np.copy(img)
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

lower_red = np.array([225, 0, 0])
upper_red = np.array([255, 200, 200])

mask = cv2.inRange(rgb, lower_red, upper_red)

cv2.imwrite('mask.png', mask)
cv2.destroyAllWindows()

img_x, img_y, _ = img.shape
mask_x, mask_y = mask.shape

x_mask = min(img_x, mask_x)
x_half_mask = mask.shape[0]//2

img_mask = mask[x_half_mask-x_mask//2 : x_half_mask+x_mask//2+1, :img_y]
plt.imshow(img_mask, cmap='Greys_r')

img_width_half = img.shape[1]//2
img_to_mask = img[:,img_width_half-x_half_mask:img_width_half+x_half_mask]
masked = cv2.bitwise_and(img_to_mask,img_to_mask,mask = img_mask)
plt.imshow(masked)

我的形象也是这些:

https://thelemonbowl.com/wp-content/uploads/2018/04/Syrian-Salad_19_WEB.jpg

感谢阅读

0 个答案:

没有答案