首页 > 解决方案 > 屏蔽图像时在函数'cv :: binary_op'中出错openCV

问题描述

我在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

谢谢你的阅读

标签: pythonopencvopencv-python

解决方案


推荐阅读