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

问题描述 投票:2回答:1

我想将椭圆拟合到图片中部分受损的物体上。 (这里的图片只是用于说明的简化示例!)

图像与损坏的椭圆形物体

通过做这个

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

所以,我已经建立了这个循环来摆脱不在椭圆上的轮廓点。

contour = largest_contours[0]
newcontour = np.zeros([1, 1, 2])
newcontour = newcontour.astype(int)
for coordinate in contour:
    if coordinate[0][0] < 600:
        newcontour = np.insert(newcontour, 0, coordinate, 0)
newellipse = cv2.fitEllipse(newcontour)

得到这个结果,这很好。

Result after trimming the contour points

问题是,我必须在很短的时间内完成很多这些工作。到目前为止,这还没有达到理想的速度。

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

编辑:

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

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

如果我不修剪轮廓并手动选择cv2.fitEllipse的轮廓,则代码需要围绕0.5s。随着轮廓修剪和三倍cv2.fitEllipse它需要围绕2s。它可能只需要1s

python opencv curve-fitting contour ellipse
1个回答
2
投票

如果对象是圆形,那么您可以在轮廓上使用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

© www.soinside.com 2019 - 2024. All rights reserved.