Search code examples
pythonopencvhaar-classifier

Getting specific image cross-section from opencv cascade with python


I'm hoping to be able to isolate a small rectangular section of the area that is returned by a haar cascade (the cascade I'm using detects faces, so for example I would like to be able to isolate just the forehead within a given face). I know that training it specifically to detect the area I want is an option, but I'm hoping that it is easy to specify an arbitrary area within the face (for example, the top 20% of the rectangle). I include the code I'm using below:

import cv2
import numpy as py
from matplotlib import pyplot as plt 

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture("resources/video/EXAMPLE.mp4")

while True:
    ret, img = cap.read()
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 9)
    for (x,y,w,h) in faces:
        cv2.rectangle(img, (x,y), (x+w, y+h), (255,0,0), 2)


    cv2.imshow('img',img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cap.destroyAllWindows()

Is there a way to manipulate/gain info about the pixels in "faces"? Any help/pointers would be hugely appreciated.


Solution

  • basicly you can divide h with 3 to getting forehead:

    for (x,y,w,h) in faces:
         cv2.rectangle(img, (x,y), (x+w, int(y+h/3)), (255,0,0), 2)
    

    but if you want to getting optimized results you can use landmark detection