使用openCV和python查找圈子

时间:2015-07-25 22:35:19

标签: python arrays opencv

我想在一个字段中找到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()

由于圆圈数组,我得到的错误是索引越界。出了什么问题?

1 个答案:

答案 0 :(得分:0)

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

在cv2.HoughCircles()调用后进行额外检查:

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