我有一个二值化图像,我已经在其上使用了打开/关闭形态学操作(这是我所能得到的最干净的图像,请相信我),看起来像这样:
如您所见,顶部有一个明显的椭圆形和一些变形。注意:我没有关于圆的大小的先验信息,并且它必须非常快地运行(我发现,HoughCircles太慢了)。我试图弄清楚如何将椭圆拟合到该椭圆,以使其最大化拟合椭圆上与该形状的边缘相对应的点的数量。也就是说,我想要这样的结果:
However, I can't seem to find a way in OpenCV to do this. Using the common tools of fitEllipse
(blue line) and minAreaRect
(green line), I get these results:
Which obviously do not represent the actual ellipse I'm trying to detect. Any thoughts as to how I could accomplish this? Happy to see examples in Python or C++.
Given the shown example image, I was very skeptical of the following statement:
which I've already used open/close morphology operations on (this is as clean as I can get it, trust me on this)
And, after reading your comment,
For precision, I need it to be fit within about 2 pixels accuracy
I was pretty sure, there might be good approximation using morphological operations.
Please have a look at the following code:
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)
The intermediate image looks like this:
And, the final result looks like this:
由于您的图片很大,我认为缩小尺寸不会对您造成伤害。以下形态学操作(大量)加速了,您的设置可能对此很感兴趣。
根据您的陈述:
注意:我没有圈的大小的先验信息[...]
您几乎可以从输入中找到上述内核大小的适当近似值。由于仅提供了一个示例图像,因此我们无法知道该问题的可变性。
希望有帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句