A.BM
A.BM

Reputation: 33

how to identify the position of detected face

I have to detect faces using openCV and python. Then identify the position of the detected face if it is in the right, the left or the middle of the screen. I already succeed to detect faces using the code below and still to know the position of the faces could someone please help me ?

  import cv2
  import sys
  import numpy as np

  face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')


  cap = cv2.VideoCapture(1)


while True:
   #capture frame by frame
   ret,frame = cap.read()

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

   faces = face_cascade.detectMultiScale(gray, 
                                      scaleFactor=1.1,
                                      minNeighbors= 5, 
                                      minSize=(30, 30), 
                                      flags=cv2.cv.CV_HAAR_SCALE_IMAGE)


   #Draw a rectangle around the faces
   for (x, y, w,h) in faces:
       cv2.rectangle(frame, (x, y), (x+w, y+h), (0,255, 0), 2)


   cv2.imshow('video',frame)

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

cap.release()
cv2.destroyAllWindows()

Upvotes: 0

Views: 3409

Answers (1)

magicleon94
magicleon94

Reputation: 5172

You could get the centre of the rectangle:

centre_x = x + w/2
centre_y = y + y/2

Then compare it with the size of the image. Assuming you have the image shape information:

height, width, channels = frame.shape #it could be gray.shape too

You can understand for example if the face is detected on the left side of the image by checking centre_x<width.

You have all the information to divide the image into a grid and understand where the rectangle places itself.

Upvotes: 4

Related Questions