从findContours中删除某些点,以便从fitEllips获得更好的结果

2024-05-16 02:38:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一个椭圆拟合到图片中一个部分损坏的物体上。(这里的图片只是简单的举例说明!)在

椭圆物体受损图像

image

通过这样做

def sort(n):
    return n.size

Image = cv2.imread('acA2500/1.jpg', cv2.IMREAD_GRAYSCALE)

#otsu binarization
_, binary = cv2.threshold(Image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

#invert binary image for opencv findContours
inverse_binary = cv2.bitwise_not(binary)

#find contours
contours, _ = cv2.findContours(inverse_binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

#sort contours by length
largest_contours = sorted(contours, key=sort, reverse=True)

#fit ellipse
contour = largest_contours[0]
ellipse = cv2.fitEllipseDirect(contour)

我得到了这个结果,这不是很令人满意。在

Result of cv2.findContours and cv2.fitEllipse

所以,我建立了这个循环来去除不在椭圆上的轮廓点。在

^{pr2}$

得到这个结果,这很好。在

Result after trimming the contour points

问题是,我必须在短时间内做很多这样的配合。到目前为止,这还没有达到预期的速度。在

有没有更好/更快/更好的方法来修剪轮廓点?由于我没有太多的编码经验,我很乐意在这里找到一些帮助:-)

我编辑了示例图片,这样现在就清楚了,不幸的是,cv2.minEnclosingCircle方法不起作用。在

现在这些图片也展示了我为什么要对轮廓进行排序。在我的真实代码中,我将一个椭圆拟合到三个最长的轮廓上,然后通过不同的程序来查看我想使用哪一个。在

如果我不修剪轮廓并手工为cv2.fitEllipse选取轮廓,代码需要大约0.5s。使用轮廓修剪和三次cv2.fitEllipse大约需要2s。可能只需要1s


Tags: image图片sortcv2物体轮廓contour椭圆
1条回答
网友
1楼 · 发布于 2024-05-16 02:38:17

如果对象是圆,则可以在轮廓上使用cv2.minEnclosingCircle来捕捉它。在

#!/usr/bin/python3
# 2019/02/13 08:50 (CST)
# https://stackoverflow.com/a/54661012/3547485

import cv2
img = cv2.imread('test.jpg')

## Convert to grayscale and threshed it
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
th, threshed = cv2.threshold(gray, 100, 255, cv2.THRESH_OTSU|cv2.THRESH_BINARY_INV)

## Find the max outers contour
cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2]
cv2.drawContours(img, cnts, -1, (255, 0, 0), 2, cv2.LINE_AA)

## Use minEnclosingCircle
(cx,cy),r = cv2.minEnclosingCircle(cnts[0])
cv2.circle(img, (int(cx), int(cy)), int(r), (0, 255, 0), 1, cv2.LINE_AA)

## This it
cv2.imwrite("dst.jpg", img)

这是我的结果。在

enter image description here

相关问题 更多 >