【问题标题】:How to know if I need to reverse the thresholding TYPE after findContour如何知道我是否需要在 findContour 之后反转阈值类型
【发布时间】:2019-07-10 09:24:05
【问题描述】:

我正在使用 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 检测指尖和缺陷,所以我需要缺陷,在第一个脱粒图像中我找不到它们,因为它反转了。请参阅第一个轮廓上的蓝点image

谢谢。

【问题讨论】:

  • findContours 在倒置二值图像上的工作原理相同,因此如果您只需要轮廓,则无需担心。
  • 好吧,我的错我忘记了一些信息,我将编辑问题。就在这里我需要检测缺陷点。

标签: python opencv opencv-contour image-thresholding


【解决方案1】:

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

  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())

【讨论】:

  • 好的,我理解算法,但我在这一行遇到了TypeError: '>' not supported between instances of 'dict_values' and 'dict_values' 异常:return max(color_counter.keys(), key=lambda x:color_counter.values())。你能解释一下它的作用吗?主要是key: lambda part ?
  • 您使用的是哪个 Python 版本?
  • python3.7.3,我想出了问题所在,我目前正在尝试解决它。当我打印color_counter.keys() 时,它返回dict_keys([255, 0]) 而不是[255, 0]
  • 所以为了避免这个错误,我将键转换为列表并且它可以工作。键:colors_keys = list(color_counter.keys())——值:colors_values = list(color_counter.values())——最大值:dominant_color = max(colors_keys, key=lambda x:colors_values)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多