OpenCV错误:bitwise_and抛出掩码和图像大小不同的错误

问题描述 投票:1回答:1

我试图在python(3.6.5)中使用openCV(3.3.1)将一个掩码应用于图像以提取所有皮肤。我正在循环拍照并检查窗口并使用两个预制的sklearm GMM对它们进行分类。如果窗口是皮肤,我将掩码的区域更改为True(255),否则将其保留为0。

我已经初始化numpy数组以在循环之前保持掩码与图像的尺寸相同,但是openCV一直说图像和掩码没有相同的尺寸(输出和错误消息在下面)。我在网站上看到过其他类似的问题,但没有一个解决方案对我有用。

这是我的代码:

# convert the image to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
delta = 6
# create an empty np array to make the mask
#mask = np.zeros((img.shape[0], img.shape[1], 1))
mask = np.zeros(img.shape[:2])
# loop through image and classify each window
for i in range(0,hsv.shape[0],delta):
    for j in range(0,hsv.shape[1],delta):
        # get a copy of the window
        arr = np.copy(hsv[i:i+delta,j:j+delta,0])
        # create a normalized hue histogram for the window
        if arr.sum() > 0:
            arr = np.histogram(np.ravel(arr/arr.sum()), bins=100, range=(0,1))
        else:
            arr = np.histogram(np.ravel(arr), bins=100, range=(0,1))
        # take the histogram and reshape it
        arr = arr[0].reshape(1,-1)
        # get the probabilities that the window is skin or not skin
        skin = skin_gmm.predict_proba(arr)
        not_skin = background_gmm.predict_proba(arr)
        if skin > not_skin:
            # becasue the window is more likely skin than not skin
            # we fill that window of the mask with ones
            mask[i:i+delta,j:j+delta].fill(255)
# apply the mask to the original image to extract the skin
print(mask.shape)
print(img.shape)
masked_img = cv2.bitwise_and(img, img, mask = mask)

输出是:

(2816, 2112)
(2816, 2112, 3)
OpenCV Error: Assertion failed ((mtype == 0 || mtype == 1) && 
_mask.sameSize(*psrc1)) in cv::binary_op, file C:\ci\opencv_1512688052760
\work\modules\core\src\arithm.cpp, line 241
Traceback (most recent call last):
File "skindetector_hist.py", line 183, in <module>
main()
File "skindetector_hist.py", line 173, in main
skin = classifier_mask(img, skin_gmm, background_gmm)
File "skindetector_hist.py", line 63, in classifier_mask
masked_img = cv2.bitwise_and(img, img, mask = mask)
cv2.error: C:\ci\opencv_1512688052760\work\modules\core\src
\arithm.cpp:241: error: (-215) (mtype == 0 || mtype == 1) && 
_mask.sameSize(*psrc1) in function cv::binary_op

正如您在输出中看到的,图像和蒙版具有相同的宽度和高度。我也试过让面具有深度一(第5行),但这没有帮助。感谢您的任何帮助!

python opencv image-processing
1个回答
0
投票

它不仅抱怨面具的大小。它抱怨面具的类型。错误:

OpenCV错误:断言失败((mtype == 0 || mtype == 1)&& _mask.sameSize(* psrc1))

意味着掩码的类型或大小(在您的情况下是相同的)是不一样的。在documentation,我们看到:

mask - 可选操作掩码,8位单通道数组,指定要更改的输出数组的元素。

这与要求类型0(CV_8U)或1(CV_8S)的错误一致。

而且,即使没有说,img也不应该是浮点数,因为它不会产生预期的结果(可能它会反正这样做)。

解决方案可能足以改变:

mask = np.zeros(img.shape[:2])

mask = np.zeros(img.shape[:2], dtype=np.uint8)

小测试显示您将获得的类型:

np.zeros((10,10)).dtype

给你dtype('float64')这意味着双打而不是8位

© www.soinside.com 2019 - 2024. All rights reserved.