用于跟踪球的Python代码 - 使用OpenCV 2.4.11

时间:2015-10-13 15:38:24

标签: python-2.7 opencv raspberry-pi2 trackball

我使用Python(OpenCV 2.4.11)2.7跟踪红球。它基于颜色检测。因此,如果有另一个具有相同颜色的非圆形物体,程序有时会失去球。因此,我希望通过添加颜色和形状来使程序更加健壮。我理解HoughCircle算法但是当我使用它时,程序不起作用。因此,我无法理解我的代码中的正确用法。我想帮助在正确的代码位置使用HoughCircle(或任何其他你认为更好的方法)。我已经在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相机和Pi 2 B板,Python OpenCV 2.4.11和基于红色的球检测。

0 个答案:

没有答案