Home > OS >  Want to capture all frames when a face is present in frame
Want to capture all frames when a face is present in frame

Time:06-30

I am trying to build a dataset of face images, I have searched and find a code that is working fine with my laptop's webcam but when I am trying to capture with IP Camera which is usually used for surveillance than code is not working.

import cv2
import numpy as np

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')

cap = cv2.VideoCapture(0)

count = 0
while True:
    ret,frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in faces:
        cv2.imwrite("frame%d.jpg" % count, frame)
        count = count   1
    if cv2.waitKey(2) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

Another thing I want to mention my laptop Camera resolution is 640.0 480.0 and IP Cameras have 2560.0 1440.0. Please help me to capture all frames when face is present.

CodePudding user response:

To capture images from specific camera you need to change arguments in cv2.VideoCapture(argument). For example:

  • cv2.VideoCapture(0): it's used to select the default camera, generally laptop inbuilt camera.
  • cv2.VideoCapture(n) where n>=1: it's used to select the other external camera connect to laptop through usb/other ports
  • cv2.VideoCapture('protocol://IP:port/1'): it's used to take input from network cameras(like in your case)
  • Here protocol means: HTTP/RTSP etc.
  • IP means hosting address: Example: 192.168.18.37
  • port where the IP address is accessed

In this case it should be:

cv2.VideoCapture('rtsp://admin:[email protected]/H264?ch=2&subtype=0/1')

CodePudding user response:

The issue has been resolved after adjusting the resolution, I have added the line of code for frame adjustment frame = cv2.resize(frame, (1360, 768)) than code has started working properly.

This code might be helpful for anyone.

import cv2
import numpy as np

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')

cap = cv2.VideoCapture('rtsp://admin:[email protected]/H264?ch=2&subtype=0/1')

count = 0
while True:
    ret,frame = cap.read()
    frame = cv2.resize(frame, (1360, 768))
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in faces:
        cv2.imwrite("frame%d.jpg" % count, frame)
        count = count   1
    if cv2.waitKey(2) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

CodePudding user response:

Changing the resolution before image capture is more optimal. There would be no need to resize every subsequent frame.

Before the while loop set the width and height as follows:

cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 768)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1380)

Different flags used for video streaming

  • Related