python - 计算机视觉 : Creating mask of hand using OpenCv and Python

标签 python opencv computer-vision

我正在尝试从手创建面具(黑色 - 背景,白色 - 手)

这是第一张原图1 :

enter image description here

这是我的代码:

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)

结果是:

enter image description here

但我需要有更好的结果 - 就像这样:

enter image description here

我该怎么办?

[编辑]

第二张不同背景的图片:

enter image description here

使用@Rotem 代码的结果:

enter image description here

1 Ajay Kumar. IIT Delhi Palmprint Image Database version 1.0. 2007

最佳答案

您可以通过在红色 channel 上应用阈值来解决它。

背景颜色为深蓝色和绿色,手色较亮且趋于红色,因此仅使用红色 channel 可能会比转换为 HSV 效果更好。

以下解决方案使用以下阶段:

  • 提取红色 channel - 使用红色 channel 作为灰度图像。
  • 使用自动选择的阈值应用二进制阈值(使用 cv2.THRESH_OTSU 参数)。
  • 使用“开放”形态学操作来清除一些小点(噪声)。
    打开相当于应用侵 eclipse 而不是扩张。
  • 使用“关闭”形态操作来关闭小间隙(我选择了圆盘形 mask )。
    关闭相当于应用扩张而不是侵 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()
    

    结果:
    enter image description here

    我认为您可以通过找到手的轮廓来改善结果,并将其逼近到具有较少顶点的多边形(但它可能是过度拟合)。

    关于python - 计算机视觉 : Creating mask of hand using OpenCv and Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60759031/

    相关文章:

    python - 调用 "dense_features_5"层时遇到异常

    opencv - 使用图像处理的头发区域边界检测

    visual-studio-2010 - 在 Windows 7 64 位上编译 OpenCV

    python - Python3中使用requests下载图片

    python - Spark 上的行明智计算

    python - 使用OpenCV保留图像中线条的 “connectedness”

    opencv - 相机平移时的单应性(用于拼接)

    opencv - OpenCV入门,API函数使用推荐

    c++ - 在 opencv 中创建晕影过滤器?

    python - 如何使用 google API for python 在特定文件夹下创建工作表?