使用openCV和python查找circles

2024-05-01 22:32:19 发布

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

我试图在一个领域中找到2个圆圈,并从我从相机获得的实时数据中标记它们。问题是houghCircles()函数无法始终检测到这些圆,即使它们的位置不变。代码如下:

import cv2
import numpy as np
import time 
wait = 5                                                                          
st = time.clock()  

on=0
arka=0
def circleS():
    circles = cv2.HoughCircles(img_grs, cv2.HOUGH_GRADIENT, 1, 20,
              param1=150,
              param2=35,
              minRadius=5,
              maxRadius=30) 
    on=0
    arka=0


    if(circles[0,0,2]>circles[0,1,2]):
        on=(circles[0,0,0],circles[0,0,1])
        arka=(circles[0,1,0],circles[0,1,1])
    if(circles[0,0,2]<circles[0,1,2]):
        on=(circles[0,1,0],circles[0,1,1])
        arka=(circles[0,0,0],circles[0,0,1])
    cv2.circle(img_bgr,on,2,(0,255,0),3)
    cv2.circle(img_bgr,arka,2,(0,0,255),3)
    return on,arka

def takePic():
    ret, frame = camera.read()
    img_bgr = np.copy(frame)                                                         
    frame = None 
    return img_bgr

camera = cv2.VideoCapture(1) 
while((time.clock()-st)<=wait):                                                
ret, frame = camera.read()                                                  # Capture a frame
    #cv2.imshow('Camera Stream',frame)                                           # Display the captured frame in a window named Camera Stream
    cv2.waitKey(1) 
cv2.destroyAllWindows()
while(1):    
    img_bgr=takePic()
    img_grs = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
    ret,img_bin = cv2.threshold(img_grs,220,255,cv2.THRESH_BINARY)
    corners = cv2.goodFeaturesToTrack(img_bin,9,0.03,3)
    corners = np.int0(corners)
    on,arka=np.int0(circleS())
    for i in corners:
        x,y = i.ravel()
        if(x>=arka[0]+15 or x<=arka[0]-15 or y>=arka[1]+15 or y<=arka[1]-15 ):
             cv2.circle(img_grs,(x,y),3,255,-1)
    cv2.imshow("Camera Stream",img_bgr) 
    cv2.waitKey(10) 
    img_bgr = None
    img_grs= None
    time.sleep(5)


camera.release()
cv2.imshow("bin",img_bgr)

cv2.waitKey(0)
cv2.destroyAllWindows()

我得到的错误是索引超出边界,因为圆数组。怎么了?在


Tags: importimgiftimeonnpcv2frame
1条回答
网友
1楼 · 发布于 2024-05-01 22:32:19

circles上的索引越界错误是因为cv2.HoughCircles()在找不到任何圆时可能返回一个空的circles数组(如您所述)。在

在cv2.HoughCircles()调用后添加一个额外的检查:

if len(circles) > 0:
    # your circle stuff

相关问题 更多 >