【发布时间】:2018-06-20 21:16:46
【问题描述】:
我正在尝试在 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 行),但这并没有帮助。感谢您的帮助!
【问题讨论】:
-
您似乎正在尝试将单通道蒙版应用于 3 通道 RGB 图像。在这种情况下,掩码也必须是 3 个通道,您可以为每个通道设置 255。您必须将图像转换为单通道灰度,或应用 3 通道蒙版。
标签: python opencv image-processing