abdou_dev
abdou_dev

Reputation: 827

Extract face from image of face extracted ( resize face extracted )

I'm trying to get the minimum possible size of a face extracted from an image, I mean, I would like to minimize the size of the drawn rectangle that detect the face. For example:

The input image:

enter image description here

The desired output:

enter image description here

Source code:

import numpy as np
import cv2

face_cascade =cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img=cv2.imread('swaa.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3,5,maxSize=(150,150))
for (x,y,w,h) in faces:
    img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    cv2.imwrite("imgg1.png",roi_color)
    cv2.imwrite("imggg1.png",roi_gray)

cv2.imshow('img',img)
cv2.imwrite("img1.png",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Image source: https://www.researchgate.net/publication/322649666_Emotion_Recognition_from_Facial_Expressions_using_Hybrid_Feature_Descriptors

Update: using the solution posted, the results are shown below:

Orginal code

After using the solution

Upvotes: 0

Views: 773

Answers (1)

Zabir Al Nazi Nabil
Zabir Al Nazi Nabil

Reputation: 11218

Just use cv2.resize function. https://www.tutorialkart.com/opencv/python/opencv-python-resize-image/

import numpy as np
import cv2
H = 64
W = 64
face_cascade =cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img=cv2.imread('swaa.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3,5,maxSize=(150,150))
for (x,y,w,h) in faces:
    img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = cv2.resize(gray[y:y+h, x:x+w], (H, W))
    roi_color = cv2.resize(img[y:y+h, x:x+w], (H,W))
    cv2.imwrite("imgg1.png",roi_color)
    cv2.imwrite("imggg1.png",roi_gray)

cv2.imshow('img',img)
cv2.imwrite("img1.png",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Upvotes: 0

Related Questions