我有一个二值化的图像,我已经使用了开放/关闭形态学操作(这是我可以得到它的清洁,相信我),看起来像这样:
正如您所看到的,顶部有一个明显的椭圆,有一些失真。注意:我没有关于圆圈大小的事先信息,而且必须非常快速地运行(HoughCircles太慢了,我发现了)。我试图弄清楚如何将椭圆拟合到它,这样它最大化拟合椭圆上与形状边缘相对应的点数。也就是说,我想要一个像这样的结果:
但是,我似乎无法在OpenCV中找到一种方法来做到这一点。使用fitEllipse
(蓝线)和minAreaRect
(绿线)的常用工具,我得到以下结果:
这显然不代表我试图检测的实际椭圆。有关如何实现这一目标的任何想法?很高兴看到Python或C ++中的示例。
鉴于显示的示例图像,我对以下声明持怀疑态度:
我已经使用了开/关形态学操作(这很干净,我可以得到它,相信我这个)
并且,在阅读您的评论后,
为了精确,我需要它适合大约2像素的精度
我很确定,使用形态学操作可能会有很好的近似。
请看下面的代码:
import cv2
# Load image (as BGR for later drawing the circle)
image = cv2.imread('images/hvFJF.jpg', cv2.IMREAD_COLOR)
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Get rid of possible JPG artifacts (when do people learn to use PNG?...)
_, gray = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)
# Downsize image (by factor 4) to speed up morphological operations
gray = cv2.resize(gray, dsize=(0, 0), fx=0.25, fy=0.25)
# Morphological Closing: Get rid of the hole
gray = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)))
# Morphological opening: Get rid of the stuff at the top of the circle
gray = cv2.morphologyEx(gray, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (121, 121)))
# Resize image to original size
gray = cv2.resize(gray, dsize=(image.shape[1], image.shape[0]))
# Find contours (only most external)
cnts, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# Draw found contour(s) in input image
image = cv2.drawContours(image, cnts, -1, (0, 0, 255), 2)
cv2.imwrite('images/intermediate.png', gray)
cv2.imwrite('images/result.png', image)
中间图像如下所示:
而且,最终结果如下:
我认为,由于您的图像非常大,因此缩小尺寸不会造成任何伤害。以下形态操作(大量)加速,这可能对您的设置感兴趣。
根据你的陈述:
注意:我没有关于圆圈大小的事先信息[...]
您可以从输入中找到适合上述内核大小的近似值。由于只给出了一个示例图像,我们无法知道该问题的可变性。
希望有所帮助!
Hough-Circle非常适合这种情况。如果您知道直径,您可以获得更好的解决方案。如果你只知道一个范围,这可能最合适:
编辑:这比拟合椭圆更好的原因是:如果你正在寻找一个圆,你应该使用一个圆作为模型。 wiki article解释了这个美丽的想法。
顺便说一句,您也可以通过打开和关闭来完成此操作。 (现在你的圈子到底有多大)
import skimage
import matplotlib.pyplot as plt
import numpy as np
from skimage import data, color
from skimage.feature import canny
from skimage.draw import circle_perimeter
from skimage.util import img_as_ubyte
from skimage.transform import hough_circle, hough_circle_peaks
image = skimage.io.imread("hvFJF.jpg")
# Load picture and detect edges
edges = canny(image, sigma=3, low_threshold=10, high_threshold=50)
# Detect two radii
hough_radii = np.arange(250, 300, 10)
hough_res = hough_circle(edges, hough_radii)
# Select the most prominent 5 circles
accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii,
total_num_peaks=3)
# Draw them
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 4))
image = color.gray2rgb(image)
for center_y, center_x, radius in zip(cy, cx, radii):
circy, circx = circle_perimeter(center_y, center_x, radius)
image[circy, circx] = (220, 20, 20)
ax.imshow(image, cmap=plt.cm.gray)
plt.show()