【发布时间】:2021-10-20 21:58:14
【问题描述】:
我们可以将代表性图片中的形状想象成桌子上随机散落的铅笔或棍子。我一直试图通过拟合椭圆来找到每个形状的区域,但我无法正确拟合椭圆。你能帮助我吗?谢谢。
第一张图片是:输入图片
我尝试过的代码,
import cv2
import numpy as np
import random as rng
import math
img = cv2.imread('sticks.png', 1)
imge= cv2.cvtColor(img,cv2.COLOR_RGB2BGR)
gray = cv2.cvtColor(imge, cv2.COLOR_BGR2GRAY)
blur = cv2.blur(gray, (2,2), 3)
rng.seed(1)
def thresh_callback(val):
threshold = val
canny_output = cv2.Canny(blur, 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)
(x,y),(minor_axis,major_axis),angle = minEllipse[i]
half_major= major_axis/2
half_minor= minor_axis/2
pixel= 37.795275591
half_major1= half_major/pixel
half_minor1= half_minor/pixel
area= math.pi * half_major1 * half_major1
print(area)
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()
第二张图是:预期结果(像这样拟合椭圆每一行)
【问题讨论】:
-
为什么您删除了问题并重新创建完全相同的问题? :)
-
@Shamshirsaz.Navid 感谢您的关注,因为我之前的问题没有答案,我需要一个答案。感谢您的关注。
标签: python opencv image-processing image-segmentation