How to Build Web Camera Recorder Using OpenCV and Flask

How to Use OpenCV to Record a Video

Let’s start with the code snippet posted on OpenCV website:

import numpy as npimport cv2cap = cv2.VideoCapture(0)# Define the codec and create VideoWriter objectfourcc = cv2.VideoWriter_fourcc(*'XVID')out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))while(cap.isOpened()):ret, frame = ret==True:frame = cv2.flip(frame,0)# write the flipped frameout.write(frame)cv2.imshow('frame',frame)if cv2.waitKey(1) & 0xFF == ord('q'):breakelse:break# Release everything if job is finishedcap.release()out.release()cv2.destroyAllWindows()
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
fourcc = cv2.VideoWriter_fourcc(*'X264')

How to Build Camera Recorder in Web Browser

The source code of video_streaming_with_flask_example is good but limited. It keeps sending responses that contain image data and never ends.

def get_frame(self):success, image = We are using Motion JPEG, but OpenCV defaults to capture raw images,# so we must encode it into JPEG in order to correctly display the# video stream.ret, jpeg = cv2.imencode('.jpg', image)return jpeg.tobytes()
def video_stream():global video_cameraglobal global_frameif video_camera == None:video_camera = VideoCamera()while True:frame = video_camera.get_frame()if frame != None:global_frame = frameyield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')else:yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + global_frame + b'\r\n\r\n')
var xhr = new XMLHttpRequest();xhr.onreadystatechange = function() {if (xhr.readyState == 4 && xhr.status == 200) {// alert(xhr.responseText);}}"POST", "/record_status");xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");xhr.send(JSON.stringify({ status: "true" }));
@app.route('/record_status', methods=['POST'])def record_status():global video_cameraif video_camera == None:video_camera = VideoCamera()json = request.get_json()status = json['status']if status == "true":video_camera.start_record()return jsonify(result="started")else:video_camera.stop_record()return jsonify(result="stopped")
class RecordingThread (threading.Thread):def __init__(self, name, camera):threading.Thread.__init__(self) = nameself.isRunning = Trueself.cap = camerafourcc = cv2.VideoWriter_fourcc(*'MJPG')self.out = cv2.VideoWriter('./static/video.avi',fourcc, 20.0, (640,480))def run(self):while self.isRunning:ret, frame = ret:self.out.write(frame)self.out.release()def stop(self):self.isRunning = Falsedef __del__(self):self.out.release()
if __name__ == '__main__''', threaded=True)

Source Code



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Xiao Ling

Xiao Ling

Manager of Dynamsoft Open Source Projects | Tech Lover