我在一个图像中得到了两个检测到的轮廓,需要顶部轮廓的两个垂直边缘之间的直径和下部轮廓的垂直边缘之间的直径。我用这个代码实现了这一点。在
import cv2
import numpy as np
import math, os
import imutils
img = cv2.imread("1.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)
edges = cv2.Canny(gray, 200, 100)
edges = cv2.dilate(edges, None, iterations=1)
edges = cv2.erode(edges, None, iterations=1)
cnts = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
# sorting the contours to find the largest and smallest one
c1 = max(cnts, key=cv2.contourArea)
c2 = min(cnts, key=cv2.contourArea)
# determine the most extreme points along the contours
extLeft1 = tuple(c1[c1[:, :, 0].argmin()][0])
extRight1 = tuple(c1[c1[:, :, 0].argmax()][0])
extLeft2 = tuple(c2[c2[:, :, 0].argmin()][0])
extRight2 = tuple(c2[c2[:, :, 0].argmax()][0])
# show contour
cimg = cv2.drawContours(img, cnts, -1, (0,200,0), 2)
# set y of left point to y of right point
lst1 = list(extLeft1)
lst1[1] = extRight1[1]
extLeft1 = tuple(lst1)
lst2 = list(extLeft2)
lst2[1] = extRight2[1]
extLeft2= tuple(lst2)
# compute the distance between the points (x1, y1) and (x2, y2)
dist1 = math.sqrt( ((extLeft1[0]-extRight1[0])**2)+((extLeft1[1]-extRight1[1])**2) )
dist2 = math.sqrt( ((extLeft2[0]-extRight2[0])**2)+((extLeft2[1]-extRight2[1])**2) )
# draw lines
cv2.line(cimg, extLeft1, extRight1, (255,0,0), 1)
cv2.line(cimg, extLeft2, extRight2, (255,0,0), 1)
# draw the distance text
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 0.5
fontColor = (255,0,0)
lineType = 1
cv2.putText(cimg,str(dist1),(155,100),font, fontScale, fontColor, lineType)
cv2.putText(cimg,str(dist2),(155,280),font, fontScale, fontColor, lineType)
# show image
cv2.imshow("Image", img)
cv2.waitKey(0)
现在我还需要上轮廓底侧的斜率线的角度。在
你知道我怎么弄到这个吗?有可能使用轮廓吗?在
或者有必要使用HoughLinesP对相关行进行排序吗?在
接下来的问题是:也许也可以得到描述这一边的抛物线斜率的函数吗?在
非常感谢你的帮助!在
有几种方法可以得到坡度。为了知道斜率,我们可以使用
cv2.HoughLines
来检测底部水平线,检测到该线的端点,并从中得到斜率。作为一个例子在代码中的
^{pr2}$edges
上给出4行,如果我们强制角度是水平的我们得到:
对于与抛物线有关的扩展问题,我们首先构造一个返回左点和右点的函数:
注意,我们可以使用这个函数来查找HoughLines返回的水平线的端点。在
因此:
让我们回到扩展的问题上,这里有左右两个点:
显然,它们不能完美地拟合抛物线,所以我们需要某种近似/拟合。为此,我们可以建立一个线性回归模型:
{cd3>我们可以得到想要的抛物线:
它给出了:
左抛物线不是完美的,但是如果需要的话,你应该算出:-)
相关问题 更多 >
编程相关推荐