trip xp
trip xp

Reputation: 21

Face Detection - Open CV can't find the face

I am learning the OpenCV. Here is my code:

import cv2
face_patterns = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
sample_image = cv2.imread('1.jpg')
gray = cv2.cvtColor(sample_image,cv2.COLOR_RGB2GRAY)
faces = face_patterns.detectMultiScale(gray,1.3,5)
print(len(faces))
for (x, y, w, h) in faces:
    cv2.rectangle(sample_image, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imwrite('result.jpg', sample_image)

If I use the picture A, I could get a lot of faces, if I use the picture B, I get none.

I changed argument in detectMultiScale(gray,1.3,5) many times, it still doesn't work.

Picture A

Picture A Result

Picture B no face

Upvotes: 1

Views: 410

Answers (3)

shreedhar
shreedhar

Reputation: 11

It uses hog as default model. You can also use cnn for better accuracy but the detection process will be slow.


cascade_classifier = cv2.CascadeClassifier('haarcascades/haarcascade_eye.xml')
cap = cv2.VideoCapture(0)

while True:
    # Capture frame-by-frame
    ret, frame = cap.read()
    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, 0)
    detections = cascade_classifier.detectMultiScale(gray,scaleFactor=1.3,minNeighbors=5)
    if(len(detections) > 0):
        (x,y,w,h) = detections[0]
        frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)

    # for (x,y,w,h) in detections:
    #   frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)

    # Display the resulting frame
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()```

Upvotes: 0

idevesh
idevesh

Reputation: 195

Instead of -

faces = face_patterns.detectMultiScale(gray,1.3,5)

Try Using -

faces = face_patterns.detectMultiScale(blackandwhite,1.3,5)

If the problem occurs even after this check out my code for face detection.

Upvotes: 0

Prakash Dahal
Prakash Dahal

Reputation: 4875

I see this more as a problem of Cv2 module itself. There are better models than HAAR CASCADES for detecting faces. face_recognition library is also very useful to detect and recognize face. It uses hog as default model. You can also use cnn for better accuracy but the detection process will be slow.

Find more here.

import cv2
import face_recognition as fr

sample_image = fr.load_image_file("1.jpg")
unknown_face_loc = fr.face_locations(sample_image, model="hog")
print(len(unknown_face_loc)) #detected face count
for faceloc in unknown_face_loc:
    y1, x2, y2, x1 = faceloc
    cv2.rectangle(sample_image, (x1, y1), (x2, y2), (0, 0, 255), 2)

sample_image = sample_image[:, :, ::-1] #converting bgr image to rbg
cv2.imwrite("result.jpg", sample_image)

Upvotes: 1

Related Questions