划定cv2.houghCircles的位置

2024-09-28 17:20:38 发布

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

有没有一个选项可以用函数cv2.HoughCircles来划分x,y坐标?在

我想找到我单击的圆;用cv2.setMouseCallback我保存了鼠标的位置,但我不知道我要传递给cv2.HoughCircles的内容。在

cv2.HoughCircles返回具有[Xposition,Yposition,radius]的数组。在

我想也许我可以处理第一个和第二个参数,但是我不知道如何访问它们,因为当我写print(circles[0])时,这三个值就会出现。在

当我写print(x)时,返回错误消息“赋值前引用的局部变量'x'”。在

有什么想法吗?在

谢谢你!在


Tags: 函数内容参数选项错误数组鼠标cv2
3条回答

你想得到圆心由cv2.setMouseCallback(方法2)给出的圆还是你想在cv2.setMouseCallback这个区域(方法1)附近的圆。在

  1. 在传递给houghCircles函数之前裁剪图像 裁剪图像=图像[y-h:y+h,x-w:x+w] 其中x和y是cv2.setMouseCallback返回的值。 根据要用于查找圆的面积大小,可以改变(h,w)

  2. 在对整个图像运行cv2.houghCircles之后,您将得到一个具有[Xposition,Yposition,radius]的数组。在

    for( size_t i = 0; i < circles.size(); i++ ){
     Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
     int radius = cvRound(circles[i][2]);
    }
    

圆[i][0]和圆[i][1]给出圆心的x和y坐标。现在可以使用cv2.setMouseCallback过滤掉想要的圆。在

^{}的文档说明:

circles Output vector of found circles. Each vector is encoded as 3 or 4 element floating-point vector (x,y,radius) or (x,y,radius,votes)

这意味着它是一个圆的向量。因此,要打印每个圆的x,y,半径,可以执行以下操作:

for circle in circles:
  print ("(x,y) = (",circle[0],",",circle[1], ") and radius =", circle[2] )

或者:

^{pr2}$

打印第一个圆。在

此外,对于鼠标位置,可以传递子图像,如:

# the position of the click as (x,y) 
mousePosition = (10,15)
# the size of the image you want to look when you click (width, height)
swz = (20,20)

#calculate the box top corner  so that is no less than 0 and the right bottom side less than image size

imgSize = img.shape
tl = (max(0, mousePosition[0] - (swz [0] / 2)), max(0, mousePosition[1] - (swz [1] / 2)))
tl = (min(tl[0], imgSize[1] - (swz [0] / 2)), min(tl[1], imgSize[0] - (swz [1] / 2)))
tl = (int(tl[0]), int(tl[1]))

circles =   cv.HoughCircles(img[tl[1]:swz[1]+tl[1], tl[0]:swz[0]+tl[0]], cv.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0   )

然后画出它们:

# make sure it found anything and make them int
circles = None if circles is None else np.uint16(np.around(circles))
cimg = cv.cvtColor(img,cv.COLOR_GRAY2BGR)
for i in circles[0,:]:
    # draw the outer circle
    cv.circle(cimg,(i[0]+tl[0],i[1]+tl[1]),i[2],(0,255,0),2)
    # draw the center of the circle
    cv.circle(cimg,(i[0]+tl[0],i[1]+tl[1]),2,(0,0,255),3)

例如:

mousePosition = (100,170)
swz = (100,100)

OpenCVlogo作为图像,我得到了这个搜索区域:

enter image description here

结果是:

enter image description here

不可能提供坐标作为cv2.HoughCircles的输入,以找到以该位置为中心的圆。相反,您可以处理返回的数组并提取包含坐标的圆。在

如您所见,circles[0]的结果给出了x坐标、y坐标和半径的所有三个参数。要提取单个参数,只需指定:

circles[0][0]将返回x坐标;
circles[0][1]将返回y坐标;并且
circles[0][2]将返回半径。在

您可以在Python中的一行中存储所有这些内容:

x, y, r = circles[0]

实际上和写作是一样的

^{pr2}$

然后使用cv2.HoughCircles中的x和y坐标并单击鼠标,您可以检查哪些圆与想要的结果匹配。在

可以使用圆的一般中心半径方程来完成此操作

(x – h)^2 + (y – k)^2 = r^2

中心在点(h,k)处。在

因此,如果(x – h)^2 + (y – k)^2 - r^2 > 0,则该点在圆之外;如果(x – h)^2 + (y – k)^2 - r^2 < 0,则该点在圆内(如果(x – h)^2 + (y – k)^2 - r^2 = 0,则该点在圆上)。在

相关问题 更多 >