簡體   English   中英

使用openCV和python查找圈子

[英]Find circles live with openCV and 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()

我遇到的錯誤是由於circle數組導致索引超出范圍。 怎么了

圓上的索引越界錯誤是因為cv2.HoughCircles()在找不到任何圓時(如您所述)可能返回空的圓數組。

在cv2.HoughCircles()調用之后進行額外檢查:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM