Ehds
Ehds

Reputation: 3

How to record the video with openCV in python?

I am unsure of how to record a video using openCV. The codes I have allow me to show the video on a html template but i am not sure which codes allow me to record the video.

-camera.py-

import cv2

class VideoCamera(object):
    def __init__(self):
        self.video =cv2.VideoCapture(1)

    def __del__(self):
        self.video.releast()

    def get_frame(self):
        ret, frame = self.video.read()

        ret, jpeg = cv2.imencode('.jpg' , frame)
        return jpeg.tobytes()

-main.py-

from camera import VideoCamera
@app.route("/Record", methods=['GET', 'POST'])
def Record():
    #return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
    return render_template('record.html')

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b' --frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame
               + b'\r\n\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()), mimetype='multipart/x-mixed-replace; boundary=frame')

-record.html-

<body>
    <img id="bg" src="{{  url_for('video_feed')  }}">
</body>

Upvotes: -1

Views: 417

Answers (1)

Vungsovanreach KONG
Vungsovanreach KONG

Reputation: 352

You will need to save each frame in a list to save them into a video file. Here is a brief code to show what you should try:

import cv2

class VideoCamera(object):
    def __init__(self):
        # Initialize the video capture and video writer objects
        self.video = cv2.VideoCapture(1)
        self.fourcc = cv2.VideoWriter_fourcc(*'XVID')
        self.out = cv2.VideoWriter('output.avi', self.fourcc, 20.0, (640, 480))

    def __del__(self):
        # Release video capture and writer objects
        self.video.release()
        self.out.release()

    def get_frame(self):
        ret, frame = self.video.read()
        if ret:
            # Write the frame into the file 'output.avi'
            self.out.write(frame)

            # Return the frame as JPEG
            ret, jpeg = cv2.imencode('.jpg', frame)
            return jpeg.tobytes()
        else:
            return None

Upvotes: -1

Related Questions