【发布时间】:2020-04-09 07:15:49
【问题描述】:
我正在尝试检测这张图片中的水管数量。为此,我正在尝试使用 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 上训练它们以执行检测?
从这里 Measuring the diameter pictures of holes in metal parts, photographed with telecentric, monochrome camera with opencv 采用答案 2 中提到的方法。我得到了这个输出。这看起来接近于执行计数,但在图像的亮度转换期间错过了许多实际管道。
【问题讨论】:
-
你的代码一开始就出错了:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)。您有蓝色管道,在提取灰度图像时利用该知识:蓝色通道将比其他通道具有更大的对比度,只需使用该通道即可。
标签: python opencv image-processing computer-vision object-detection