0

Does anyone know how to use the video writer? I have a simple script that will detect faces with haar_cascades with laptop webcam and I am trying to figure out how write the output to a video file with the boxes around the detected faces. The .xml file for haar cascade is saved to directory and program runs in a loop format. What I have commented out below is #cv2.VideoWriter.write(frame) which is not working as the video writer is not expecting a numpy array.

import numpy as np
import cv2, time
import matplotlib.pyplot as plt

haar_face_cascade = cv2.CascadeClassifier('opencv-master/opencv-master/data/haarcascades/haarcascade_frontalface_alt.xml')
video = cv2.VideoCapture(0)  
a = 0


while True:

    a = a + 1    
    check, frame = video.read()

    print(check)
    print(frame)

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = haar_face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5);
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2)


    cv2.imshow("Face Detector", frame)
    #cv2.VideoWriter.write(frame)


    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

print(a)

video.release()
cv2.destroyAllWindows()
bbartling
  • 3,288
  • 9
  • 43
  • 88
  • Have a look at [How to write video file in OpenCV 2.4.3](https://stackoverflow.com/questions/13623394/how-to-write-video-file-in-opencv-2-4-3), that uses the C++ API but the functions are the same. You need to create an instance, open it and ten you can `write` to it – GPhilo Jun 25 '18 at 14:21

1 Answers1

0

So I did some research and figured it out.... https://docs.opencv.org/3.1.0/dd/d43/tutorial_py_video_display.html

import numpy as np
import cv2


haar_face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
video = cv2.VideoCapture(0)  
a = 0

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

while True:


    a = a + 1    
    check, frame = video.read()


    print(frame)

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = haar_face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5);
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2)

    out.write(frame)
    cv2.imshow("Face Detector", frame)


    key = cv2.waitKey(1)    
    if key == ord('q'):
        break

print(a)

video.release()
out.release()
cv2.destroyAllWindows()
bbartling
  • 3,288
  • 9
  • 43
  • 88