我正在尝试从手创建面具(黑色 - 背景,白色 - 手)
这是第一张原图1 :
这是我的代码:
hand = cv2.imread('hand.jpg')
blur = cv2.GaussianBlur(hand, (3, 3), 0)
hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)
mask2 = cv2.inRange(hsv, np.array([2, 0, 0]), np.array([20, 255, 255]))
kernel = np.ones((7, 7))
dilation = cv2.dilate(mask2, kernel, iterations=1)
erosion = cv2.erode(dilation, kernel, iterations=1)
filtered = cv2.GaussianBlur(erosion, (5, 5), 0)
ret, thresh = cv2.threshold(filtered, 90, 255, 0)
cv2.imshow('Threshold', thresh)
结果是:
但我需要有更好的结果 - 就像这样:
我该怎么办?
[编辑]
第二张不同背景的图片:
使用@Rotem 代码的结果:
1 Ajay Kumar. IIT Delhi Palmprint Image Database version 1.0. 2007
最佳答案
您可以通过在红色 channel 上应用阈值来解决它。
背景颜色为深蓝色和绿色,手色较亮且趋于红色,因此仅使用红色 channel 可能会比转换为 HSV 效果更好。
以下解决方案使用以下阶段:
cv2.THRESH_OTSU
参数)。 打开相当于应用侵 eclipse 而不是扩张。
关闭相当于应用扩张而不是侵 eclipse 。
这是代码:
import cv2
img = cv2.imread('hand.jpg')
# Extract red color channel (because the hand color is more red than the background).
gray = img[:, :, 2]
# Apply binary threshold using automatically selected threshold (using cv2.THRESH_OTSU parameter).
ret, thresh_gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# Use "opening" morphological operation for clearing some small dots (noise)
thresh_gray = cv2.morphologyEx(thresh_gray, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3)))
# Use "closing" morphological operation for closing small gaps
thresh_gray = cv2.morphologyEx(thresh_gray, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9,9)))
# Display result:
cv2.imshow('thresh_gray', cv2.resize(thresh_gray, (thresh_gray.shape[1]//2, thresh_gray.shape[0]//2)))
cv2.waitKey(0)
cv2.destroyAllWindows()
结果:
我认为您可以通过找到手的轮廓来改善结果,并将其逼近到具有较少顶点的多边形(但它可能是过度拟合)。
关于python - 计算机视觉 : Creating mask of hand using OpenCv and Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60759031/