如何知道我是否需要在 findContour 之后反转阈值类型

How to know if I need to reverse the thresholding TYPE after findContour

我正在使用 OpenCV 进行手部检测。但是我在尝试绘制脱粒图像的轮廓时遇到了困难。 findContour 将始终尝试找到白色区域作为轮廓。

所以基本上它在大多数情况下都有效,但有时我的脱粒图像看起来像这样:

_, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)

因此,要使其正常工作,我只需要更改阈值类型 cv2.THRESH_BINARY_INV

_, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)

而且效果很好。

我的问题是如何确定何时需要反转阈值?我是否需要始终在两个脱粒图像上找到轮廓,并比较结果(我在这种情况下如何?)?或者有一种方法可以缓解知道是否完全错过了轮廓。

编辑:有一种方法可以 100% 确定轮廓看起来像一只手吗?

编辑 2 :所以我忘了提到我正在尝试使用此 method so I need defects, which with the first threshed image I can't find them, because it reversed. See blue point on the First contour image.

检测指尖和缺陷

谢谢。

您可以编写一个实用方法来检测边界上最主要的颜色,然后决定逻辑,就好像您是否要反转图像一样,所以流程可能如下所示:

  1. 使用OSTU二值化方法。
  2. 将阈值图像传递给实用方法get_most_dominant_border_color并获得主色。
  3. 如果边框颜色是 WHITE,那么您应该使用 cv2.bitwise_not 反转图像,否则只保持原样。

get_most_dominant_border_color可以定义为:

from collections import Counter

def get_most_dominant_border_color(img):
    # Get the top row
    row_1 = img[0, :]
    # Get the left-most column
    col_1 = img[:, 0]
    # Get the bottom row
    row_2 = img[-1, :]
    # Get the right-most column
    col_2 = img[:, -1]

    combined_li = row_1.tolist() + row_2.tolist() + col_1.tolist() + col_2.tolist()

    color_counter = Counter(combined_li)

    return max(color_counter.keys(), key=lambda x:color_counter.values())