Search code examples
pythonopencvface-detection

Decreasing the image size after Face Detection


I tried this face detection program that uses haarcascades in opencv.I was able to get the required output (Finding the number of faces in the provided image), but there is a slight problem with the resultant image which draws rectangles around the faces.Instead of the original image the output image is a zoomed version of the original which doesn't show the entirety of it.

Sample

Input:enter image description here

Output: enter image description here

So this is what the output looks like after the program is run.

The code:

import cv2
import sys

# Get user supplied values
imagePath = sys.argv[1]
cascPath = "haarcascade_frontalface_default.xml"

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)

# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Detect faces in the image
faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.2,
    minNeighbors=5,
    minSize=(30,30)

)

print("Found {0} faces!".format(len(faces)))

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

cv2.imshow("Faces found", image)
cv2.waitKey(0)

In the prompt:

C:\Myproject>python main.py NASA.jpg
Found 20 faces!

Program gives more or less the correct answer.The scale factor can be modified to get accurate results. So my question is what can be done to get a complete image in the output?Please add any other suggestions too,I'll be thankful. Thanks for reading!

EDIT:

After a suggestion i used imwrite and saved the output image which seems very fine,but still the displayed image after running the program remains same.

Saved Image- enter image description here


Solution

  • Your image is too big to be displayed on your screen. Add: cv2.namedWindow('Faces found', cv2.WINDOW_NORMAL) before cv2.imshow("Faces found", image) That line will create resizeable window.