0

The code of live stream face detection using haarcascade_frontalface_default.xml with IP camera working well but unwanted images capture and save in the same folder, I don't want unwanted images of random empty space. I am using haarcascade_frontalface_default.xml twice still the same result so give me a solution

import cv2
import datetime
import os
import random
if not os.path.exists('./dataset'):
    os.makedirs('./dataset')
    cap = 
    cv2.VideoCapture("rtsp://admin:admin@192.168.0.7:554/cam/realmonitor? 
    channel=1&subtype=0")
    face_cascade = 
    cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    def getfilename():
        x = datetime.datetime.now()
        filename = 
        x.strftime("%d")+x.strftime("%m")+x.strftime("%Y")+x.strftime("%H")+
        x.strftime("%M")+x.strftime("%S")+"- 
        "+str(random.randint(1,300))+".jpg"
        return filename

while 1:
    ret, img = cap.read()
    faces = face_cascade.detectMultiScale(img, 1.3, 5)
    for (x,y,w,h) in faces: 
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

        roi_gray = img[y:y+h, x:x+w]
        cv2.imwrite("E:/python_pro/dataset/"+getfilename(),roi_gray) 
    cv2.imshow('img',img)
    k = cv2.waitKey(1) & 0xff
    if k == 27: 
        break

cap.release()
cv2.destroyAllWindows()
Sreekiran A R
  • 3,123
  • 2
  • 20
  • 41
Mrunali
  • 1
  • 2

1 Answers1

1

First of all the line face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') means you are initialsing the face detector, it does not mean you are doing a face detection. So the two lines inside the loop is unnecessary. The function detectMultiScale is what does the face detection. You are getting unwanted images because you have set the confidence of classifier, MinNeigbours=5. You can avoid false positives by increasing the MinNeigbours to 15 and try.

ret, img = cap.read()
faces = face_cascade.detectMultiScale(img, 1.3, 15)
for (x,y,w,h) in faces: 
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

    roi_gray = img[y:y+h, x:x+w]
    cv2.imwrite("E:/python_pro/dataset/"+getfilename(),roi_gray) 
cv2.imshow('img',img)
k = cv2.waitKey(1) & 0xff
if k == 27: 
    break

You can check my answer at how to limit number of faces detected by haar cascades Also. see the official documentation https://docs.opencv.org/2.4/modules/objdetect/doc/cascade_classification.html

Sreekiran A R
  • 3,123
  • 2
  • 20
  • 41