[英]Circular contour detection in an image python opencv
我正在尝试在下图中检测到圆圈。
所以我做了颜色阈值,最后得到了这个结果。
因为中心的线被去掉了,圆被分成了很多小部分,所以如果我在这个上面做轮廓检测,它只能分别给我每个轮廓。
但是有没有办法我可以以某种方式组合轮廓,这样我就可以得到一个圆圈而不是它的一部分?
这是我的颜色阈值代码:
blurred = cv2.GaussianBlur(img, (9,9), 9)
ORANGE_MIN = np.array((12, 182, 221),np.uint8)
ORANGE_MAX = np.array((16, 227, 255),np.uint8)
hsv_disk = cv2.cvtColor(blurred,cv2.COLOR_BGR2HSV)
disk_threshed = cv2.inRange(hsv_disk, ORANGE_MIN, ORANGE_MAX)
我猜颜色分割的阈值有问题,所以这里的想法是生成一个二进制掩码。 通过检查您感兴趣的区域似乎比输入图像的其他区域更亮,因此可以简单地对灰度图像进行阈值处理以简化上下文。 注意:您可以根据您的要求更改此步骤。 在满足阈值输出后,您可以使用cv2.convexHull()
来获得轮廓的凸面形状。
还要记住选择最大的轮廓并忽略小轮廓。 以下代码可用于生成所需的输出:
import cv2
import numpy as np
# Loading the input_image
img = cv2.imread("/Users/anmoluppal/Downloads/3xGG4.jpg")
# Converting the input image to grayScale
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Thresholding the image to get binary mask.
ret, img_thresh = cv2.threshold(img_gray, 145, 255, cv2.THRESH_BINARY)
# Dilating the mask image
kernel = np.ones((3,3),np.uint8)
dilation = cv2.dilate(img_thresh,kernel,iterations = 3)
# Getting all the contours
_, contours, __ = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# Finding the largest contour Id
largest_contour_area = 0
largest_contour_area_idx = 0
for i in xrange(len(contours)):
if (cv2.contourArea(contours[i]) > largest_contour_area):
largest_contour_area = cv2.contourArea(contours[i])
largest_contour_area_idx = i
# Get the convex Hull for the largest contour
hull = cv2.convexHull(contours[largest_contour_area_idx])
# Drawing the contours for debugging purposes.
img = cv2.drawContours(img, [hull], 0, [0, 255, 0])
cv2.imwrite("./garbage.png", img)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.