import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while (1):

    _, frame = cap.read()

    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    lower_green = np.array([40, 50, 50])
    upper_green = np.array([80, 102, 200])

    # Threshold the HSV image to get only green colors
    mask = cv2.inRange(hsv, lower_green, upper_green)

    total_pixels = mask.shape[0] * mask.shape[1]
    print "Number of pixels: %", total_pixels

    pixel_counter = 0
    x_counter = 0
    y_counter = 0
    for y in xrange(640):
        for x in xrange(480):
            pixel = mask[x, y]
            if pixel == 255:
                pixel_counter += 1
                x_counter += x
                y_counter += y
    x_center = x_counter / pixel_counter
    y_center = y_counter / pixel_counter
    print x_center, y_center

    cv2.line(frame, (x_center+15, y_center), (x_center+2, y_center), (235, 218, 100), 1)
    cv2.line(frame, (x_center-15, y_center), (x_center-2, y_center), (235, 218, 100), 1)
    cv2.line(frame, (x_center, y_center+15), (x_center, y_center+2), (235, 218, 100), 1)
    cv2.line(frame, (x_center, y_center-15), (x_center, y_center-2), (235, 218, 100), 1)

    cv2.circle(frame, (x_center, y_center), 4, (235, 218, 100), 2)

    cv2.imshow('frame', frame)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

track the green color

By Vik.victory, 2017-06-23 19:10:32