Ask Your Question
0

Locating color in video frame - python

asked 2014-04-05 11:25:51 -0600

ss32 gravatar image

updated 2014-04-05 11:26:56 -0600

I'm trying to locate a given color within the frame and compare its location to a given value, ideally I would like a color range. Right now I would like to know if it's on the left or the right hand side of the frame. I'm able to do this for a single frame using a really slow search method and I feel like there has to be a more efficient way of doing this using an opencv function.

Here's what I'm currently using

# Searches an image for a given color and plots results


import cv2 
import pylab as p

# Import the image
im = cv2.imread('orange.jpg')

width = len(im[0,:])
height = len(im[:,0])

# Define color
B = 34
G = 36
R = 36

result_x = []
result_y = []
for i in range(height):
    for j in range(width):
        for k in range(2):
            if (im[i,j,0]==B and im[i,j,1]==G and im[i,j,2]==R):

                result_x.append(j)
                result_y.append(i)


p.plot(result_x,result_y,'ro')
p.xlim(0,width)
p.ylim(0,height)
p.gca().invert_yaxis()
p.show()
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2014-04-07 19:30:26 -0600

ss32 gravatar image

updated 2014-04-07 19:30:46 -0600

In case someone finds this in a search, I came up with a functional, albeit slow, method.

import cv2
import numpy as np
import serial


cap = cv2.VideoCapture(1)

loc = input('ACM: ')
ser = serial.Serial('/dev/ttyACM'+str(loc), 9600)

while(1):

    # Take each frame
    _, frame = cap.read()
    width = len(frame[0,:])
    # Convert BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # Define color range for masking
    lower = np.array([110,100,100])
    upper = np.array([130,255,255])

    # Threshold the HSV image to get only blue colors
    mask = cv2.inRange(hsv, lower, upper)

    # Bitwise-AND mask and original image
    result = cv2.bitwise_and(frame,frame, mask= mask)

    gray = cv2.cvtColor(result,cv2.COLOR_BGR2GRAY)

        #(image, max corners, quality level, minimum distance, mask)
    corners = cv2.goodFeaturesToTrack(gray,4,0.01,10)
    corners = np.int0(corners)

    for i in corners:

        x_array = []
        y_array = []


        x,y = i.ravel()
        cv2.circle(result,(x,y),3,255,-1)

        x_array.append(x)
        y_array.append(y)
        # Compare the average value of the X position to the midpoint of the frame
        # and print its relative location
        if (np.mean(x_array) <= int(width/2)):

            print 'left'

        else: 

            print 'right'


    #cv2.imshow('res',result)
    if cv2.waitKey(3) & 0xFF == ord('q'):
        break
        ser.write(str(chr(2)))
        break


cv2.destroyAllWindows()
edit flag offensive delete link more

Question Tools

Stats

Asked: 2014-04-05 11:25:51 -0600

Seen: 1,684 times

Last updated: Apr 07 '14