【发布时间】:2021-10-10 06:40:33
【问题描述】:
这是我在 Stackoverflow 上的第一个问题。我有点激动,如果我错了,请原谅我。我们混合了从油漆中随机绘制的有和没有重叠的椭圆。我正在分享我正在处理的图像和我的代码。我不是 opencv 模块的专业人士,我编写代码是受源代码启发的研究结果。
我的代码的目的是,
使用 cv2.fitEllipse 方法检测带有和不带有重叠椭圆的随机绘制。接下来,找到检测到的椭圆的长轴、短轴和面积。
我的代码的问题其实是这样的,
在重叠椭圆中,在正常情况下拟合椭圆时,应该拟合2个椭圆,但拟合大约6-7个椭圆,我无法达到我想要计算的值。
我愿意为您提供帮助,在此先感谢您。
import cv2
import numpy as np
import random as rng
import math
img = cv2.imread('overlapping_ellipses.png', 1)
imge= cv2.cvtColor(img,cv2.COLOR_RGB2BGR)
gray = cv2.cvtColor(imge, cv2.COLOR_BGR2GRAY)
blur = cv2.blur(gray, (2,2), 3)
edged = cv2.Canny(blur, 50, 100)
kernel= np.ones((2,2))
edged1 = cv2.dilate(edged, kernel, iterations=2)
edged2 = cv2.erode(edged1, kernel, iterations=2)
def thresh_callback(val):
threshold = val
canny_output = cv2.Canny(edged2, threshold, threshold * 4)
contours, _ = cv2.findContours(canny_output, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
minRect = [None]*len(contours)
minEllipse = [None]*len(contours)
for i, c in enumerate(contours):
minRect[i] = cv2.minAreaRect(c)
if c.shape[0] > 5:
minEllipse[i] = cv2.fitEllipse(c)
(x1,y1),(d1,d2),angle = minEllipse[i]
print('\nX1: ', round(x1,4), '\nY1: ', round(y1,4), '\nD1:',round(d1,4), '\nD2',round(d2,4), '\nAngle:', round(angle,4))
long= x1-d2
small= y1-d1
major= long/2
minor= small/2
pixel= 37.795275591
major1= major/pixel
minor1= minor/pixel
print('--------------------------------')
print('Major axis is: ', abs(round(major1,4)), 'cm')
print('Minor axis is: ', abs(round(minor1,4)), 'cm')
print('--------------------------------')
drawing = np.zeros((canny_output.shape[1], canny_output.shape[1], 3), dtype=np.uint8)
for i, c in enumerate(contours):
color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256))
cv2.drawContours(drawing, contours, i, color)
if c.shape[0] > 5:
cv2.ellipse(drawing, minEllipse[i], color, 1)
cv2.imshow('Fitting Ellips', drawing)
source_window = 'Source'
cv2.namedWindow(source_window)
cv2.imshow(source_window, img)
max_thresh = 255
thresh = 100
cv2.createTrackbar('Canny Thresh:', source_window, thresh, max_thresh, thresh_callback)
thresh_callback(thresh)
cv2.waitKey()
【问题讨论】:
-
您的图像是否真正具有代表性,并且您的椭圆都是垂直或水平定向的,而不是对角线或任何其他角度?
-
单个椭圆是凸的,两个重叠椭圆的形状不是。我可能会尝试确定两个椭圆的轮廓相交的 4 个点......也许寻找凸面缺陷?这样,您可以将轮廓分成 4 块,每个“叶”一个。然后尝试在两个相对叶的点上拟合一个椭圆。
-
这是我在之前评论中概述的想法的当前原型:pastebin.com/ki8CMj6k |这是它为 2 椭圆场景之一生成的可视化:i.imgur.com/Ml12Kc5.png - 红色显示了两个单独椭圆的拟合。
标签: python opencv area ellipse