【发布时间】:2020-07-07 11:13:05
【问题描述】:
因为我正在尝试在 Python 中使用 OpenCV 来提高我的技能,所以我想知道从大部分是深色的图像中提取特定灰色调的最佳方法是什么。
首先,我创建了一个测试图像,以便使用 OpenCV 测试不同的方法:
假设我想在此图像中提取特定颜色并为其添加边框。现在我选择了中间的灰色矩形,颜色为 (33, 33, 34 RGB),见下图:
(这是没有红色边框的图像,以便您测试您的想法:https://i.stack.imgur.com/Zf8Vb.png)
这是我迄今为止尝试过的,但效果不佳:
img = cv2.imread(path) #Read input image
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # Convert from BGR to HSV color space
saturation_plane = hsv[:, :, 1] # all black/white/gray pixels are zero, and colored pixels are above zero
_, thresh = cv2.threshold(saturation_plane, 8, 255, cv2.THRESH_BINARY) # Apply threshold on s
contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # draw all contours
contours = contours[0] if len(contours) == 2 else contours[1]
result = img.copy()
for contour in contours:
(x, y, w, h) = cv2.boundingRect(contour) # compute the bounding box for the contour
if width is equal to the width of the rectangle i want to extract:
draw contour
如果矩形的大小不固定,我无法通过它的宽度/高度来检测它怎么办?此外,将图像转换为灰度而不是HSV更好吗?我刚接触它,我想听听你实现这一目标的方法。
提前致谢。
【问题讨论】:
标签: python opencv python-imaging-library crop contour