检测图像中的多个圆圈

Detect multiple circles in an image

我正在尝试检测这张图片中水管的数量。为此,我尝试使用 OpenCV 和基于 Python 的检测。我得到的结果让我有点困惑,因为圈子的分布太大而且不准确。

代码

import numpy as np
import argparse
import cv2

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help = "Path to the image")
args = vars(ap.parse_args())

# load the image, clone it for output, and then convert it to grayscale
image = cv2.imread(args["image"])
output = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

#detect circles in the image
#circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, param1=40,minRadius=10,maxRadius=35)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 8.5,70,minRadius=0,maxRadius=70)

#print(len(circles[0][0]))
# ensure at least some circles were found
if circles is not None:
    # convert the (x, y) coordinates and radius of the circles to integers
    circles = np.round(circles[0, :]).astype("int")
    # count = count+1   

    # print(count) 

    # loop over the (x, y) coordinates and radius of the circles
    for (x, y, r) in circles:
        # draw the circle in the output image, then draw a rectangle
        # corresponding to the center of the circle
        cv2.circle(output, (x, y), r, (0, 255, 0), 4)
        cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)

    # show the output image
   # cv2.imshow("output", np.hstack([output]))
    cv2.imwrite('output.jpg',np.hstack([output]),[cv2.IMWRITE_JPEG_QUALITY, 70])
    cv2.waitKey(0)

在我 运行 之后,我确实看到检测到很多圆圈,但是,结果完全乱七八糟。 我的问题是,我该如何改进这种检测。 HoughCircles 方法中具体需要优化哪些参数以获得更高的精度?或者,我是否应该采用通过边界框注释数百张相似图像的方法,然后在像 Yolo 这样的成熟 CNN 上训练它们来执行检测?

采用此处 的答案 2 中提到的方法。我得到了这个输出。这看起来接近于执行计数,但在图像亮度变换期间错过了很多实际管道。

您的 HoughCircles 调用最重要的参数是:

  1. param1:因为您使用的是cv2.HOUGH_GRADIENT,所以param1是边缘检测算法的较高阈值,param1 / 2是较低阈值。
  2. param2:表示累加器阈值,数值越低,返回的圈数越多。
  3. minRadiusmaxRadius:示例中的蓝色圆圈的直径大约为 20 像素,因此 maxRadius 使用 70 像素是为什么有这么多圆圈的原因由算法返回。
  4. minDist: 两个圆心之间的最小距离

参数化定义如下:

circles = cv2.HoughCircles(gray,
                           cv2.HOUGH_GRADIENT,
                           minDist=6,
                           dp=1.1,
                           param1=150,
                           param2=15,
                           minRadius=6,
                           maxRadius=10)

returns:

你可以做一个自适应阈值作为预处理。这基本上是在寻找比相邻像素相对更亮的区域,您的全局阈值会丢失一些管道,这会使它们更好一些。

import cv2
import matplotlib.pyplot as plt
import numpy as np

img = cv2.imread('a2MTm.jpg')
blur_hor = cv2.filter2D(img[:, :, 0], cv2.CV_32F, kernel=np.ones((11,1,1), np.float32)/11.0, borderType=cv2.BORDER_CONSTANT)
blur_vert = cv2.filter2D(img[:, :, 0], cv2.CV_32F, kernel=np.ones((1,11,1), np.float32)/11.0, borderType=cv2.BORDER_CONSTANT)
mask = ((img[:,:,0]>blur_hor*1.2) | (img[:,:,0]>blur_vert*1.2)).astype(np.uint8)*255

plt.imshow(mask)

然后您可以继续相同的 post 处理步骤。


以下是一些示例处理步骤:

circles = cv2.HoughCircles(mask,
                           cv2.HOUGH_GRADIENT,
                           minDist=8,
                           dp=1,
                           param1=150,
                           param2=12,
                           minRadius=4,
                           maxRadius=10)
output = img.copy()
for (x, y, r) in circles[0, :, :]:
  cv2.circle(output, (x, y), r, (0, 255, 0), 4)

您可以调整参数以获得您想要的,阅读参数 here

不使用 cv2.HoughCircles 另一种方法是使用轮廓过滤。我们可以对图像进行阈值处理,然后使用纵横比、轮廓区域和斑点半径进行过滤。结果如下:

Count: 344

代码

import cv2

image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,27,3)

cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
count = 0
for c in cnts:
    area = cv2.contourArea(c)
    x,y,w,h = cv2.boundingRect(c)
    ratio = w/h
    ((x, y), r) = cv2.minEnclosingCircle(c)
    if ratio > .85 and ratio < 1.20 and area > 50 and area < 120 and r < 7:
        cv2.circle(image, (int(x), int(y)), int(r), (36, 255, 12), -1)
        count += 1

print('Count: {}'.format(count))

cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()