1

我正在使用 Python (OpenCV 2.4.11) 2.7 来跟踪红球。它基于颜色检测。因此,如果有另一个具有相同颜色的非圆形物体,程序有时会丢失球。因此,我希望通过添加颜色和形状使程序更加健壮。我了解 HoughCircle 算法,但是当我使用它时,程序不起作用。因此我无法理解我的代码中的正确用法。我想获得帮助以在代码的正确位置使用 HoughCircle(或您认为更好的任何其他 f)。我已经在 stackoverflow 上搜索了其他主题,但是它在 C、C++ 或旧 OpenCV 中的某些库支持不再可用。帮助表示赞赏。

import numpy as np
import cv2
import time
import os
# This system command loads the right drivers for the Raspberry Pi camera
os.system('sudo modprobe bcm2835-v4l2')
w=480
h=320
my_camera = cv2.VideoCapture(0)
my_camera.set(3,w)
my_camera.set(4,h)
time.sleep(2)
while (True):
    success, image = my_camera.read()
    image = cv2.flip(image,-1)
    image = cv2.GaussianBlur(image,(5,5),0)
    image_HSV = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
    lower_pink = np.array([0,220,20])
    upper_pink = np.array([15,255,190])
    mask = cv2.inRange(image_HSV,lower_pink,upper_pink)
    mask = cv2.GaussianBlur(mask,(5,5),0)
    # findContours returns a list of the outlines of the white shapes in the       mask (and a heirarchy that we shall ignore)
    contours, hierarchy =        cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    # If we have at least one contour, look through each one and pick the biggest
    if len(contours)>0:
        largest = 0
        area = 0
        for i in range(len(contours)):
            # get the area of the ith contour
            temp_area = cv2.contourArea(contours[i])
            # if it is the biggest we have seen, keep it
            if temp_area > area:
                area = temp_area
                largest = i
        # Compute the coordinates of the center of the largest contour
        coordinates = cv2.moments(contours[largest])
        target_x = int(coordinates['m10']/coordinates['m00'])
        target_y = int(coordinates['m01']/coordinates['m00'])
        # Pick a suitable diameter for our target (grows with the contour)
        diam = int(np.sqrt(area)/4)
        # draw on a target
        cv2.circle(image,(target_x,target_y),diam,(0,255,0),1)
        cv2.line(image,(target_x-2*diam,target_y),(target_x+2*diam,target_y),(0,255,0),1)
        cv2.line(image,(target_x,target_y-2*diam),(target_x,target_y+2*diam),(0,255,0),1)
    cv2.imshow('View',image)
    # Esc key to stop, otherwise repeat after 3 milliseconds
    key_pressed = cv2.waitKey(3)
    if key_pressed == 27:  
        break
cv2.destroyAllWindows()
my_camera.release()
# due to a bug in openCV you need to call wantKey three times to get the window to dissappear properly. Each wait only last 10 milliseconds
cv2.waitKey(10)
time.sleep(0.1)
cv2.waitKey(10)
cv2.waitKey(10)

我正在使用带有 Pi 2 B 板、Python OpenCV 2.4.11 和基于红色的球检测的 Pi 相机。

4

0 回答 0