如何根据特定的颜色轮廓或边框找到轮廓?

How to find Contour based on specific color outline or border?

我正在尝试根据下面显示的 AutoCAD 绘图中的黄色轮廓来检测轮廓数。

import numpy as np
import cv2

image = cv2.imread('C:/Users/htc/Desktop/capture.png')
original = image.copy()
image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower = np.array([0, 208, 94], dtype="uint8")
upper = np.array([179, 255, 232], dtype="uint8")
mask = cv2.inRange(image, lower, upper)

# Find contours
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Extract contours depending on OpenCV version
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

# Iterate through contours and filter by the number of vertices 
for c in cnts:
   perimeter = cv2.arcLength(c, True)
   approx = cv2.approxPolyDP(c, 0.04 * perimeter, True)
   if len(approx) > 5:
       cv2.drawContours(original, [c], -1, (36, 255, 12), -1)

cv2.imshow('mask', mask)
cv2.imshow('original', original)
cv2.waitKey()

我期望检测到这两个轮廓圆(轮廓)但未实现的输出。任何人都可以在我做错的地方帮助我。

输出

您的上边界检测不到圆圈的颜色。 尝试将其设置为如下所示:

upper = np.array([179, 255, 255], dtype="uint8")

随意调整边界以 select 您的颜色。

黄色的色调值与其他颜色不同。您可以使用第一个通道(色调),取值范围是10:15

lower = np.array([10, 0, 0], dtype="uint8") 
upper = np.array([15, 255, 255], dtype="uint8")

色调通道指示图像的“颜色”see this。您可以显示色调通道

hue = image[:,:,0]
cv2.imshow('hue', hue)

快黑了。让我们“重新调整”它的值:

cv2.imshow('hue', (hue-np.min(hue))/(np.max(hue)-np.min(hue))*255)

用MS Paint找到“white zone”的范围后,我看到是170-255np.max(hue) = 15, np.min(hue) = 0,所以原来的范围是10-15.

这就是我在 lowerupper 中得到数字的方式。由于您只关心颜色,因此 lower 的其他通道设置为 0,0upper

的通道设置为 255,255