TigerC
TigerC

Reputation: 161

How to detect only the left eye in a video with opencv?

I want to detect only the left eye in a video streaming, but I can't. When I run this code, it detects two eyes (right and left) and sometimes it also detects the mouth or the nose like it is an eye.

Follow the code below:

import cv2
import numpy as np

faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
#eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_lefteye_2splits.xml')

video_capture = cv2.VideoCapture(0)

while True:
    ret, img = video_capture.read()
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray_img,
        scaleFactor=1.98,
        minNeighbors=8,
        minSize=(80, 80),
        flags=cv2.cv.CV_HAAR_SCALE_IMAGE    
    )    

    #print 'faces: ', faces
    for (p,q,r,s) in faces:
        #cv2.rectangle(img,(p,q),(p+r,q+s),(255,0,0),3)
        face_gray = gray_img[q:q+s, p:p+r]
        face_color = img[q:q+s, p:p+r]
        eyes = eye_cascade.detectMultiScale(face_gray)
        for (ep,eq,er,es) in eyes:
            cv2.rectangle(face_color,(ep,eq),(ep+er,eq+es), (0,255,0),3)

    rimg = cv2.flip(img, 1) # invert the object img
    cv2.imshow("Video", rimg)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video_capture.release()
cv2.destroyAllWindows()

So how should I do to detect only the left eye?

PS: I'm using Python 2.7.13, NumPy 1.10.0 and OpenCV 2.4.13.3 in this program.

Upvotes: 1

Views: 2337

Answers (1)

codein
codein

Reputation: 11

You can use a simple for loop to iterate through the eyes returned by eye-cascade and find the index of the eye with minimum x-coordinate. That will give you the index of the left-most eye.

def getleftmosteye(eyes):
 leftmost=9999999
 leftmostindex=-1
  for i in range(0,2):
   if eyes[i][0]<leftmost:
    leftmost=eyes[i][0]
    leftmostindex=i
  return eyes[leftmostindex]

Now you can get coordinates of the left eye once get its index.

Upvotes: 1

Related Questions