Python OpenCV | Saving a video














































Python OpenCV | Saving a video



Saving a Video


So we capture a video, process it frame-by-frame and we want to save that video. For images, it is very simple, just use cv2.imwrite(). Here a little more work is required. 

This time we create a VideoWriter object. We should specify the output file name (eg: output.avi). Then we should specify the FourCC code (details in next paragraph). Then number of frames per second (fps) and frame size should be passed. And last one is isColor flag. If it is True, encoder expect color frame, otherwise it works with grayscale frame. 

FourCC is a 4-byte code used to specify the video codec. The list of available codes can be found in fourcc.org. It is platform dependent.

Code :

import cv2
import numpy as np

class SaveVideo:
def __init__(
self, camera_key):
self.camera_key = camera_key

def Save_Video(
self):

self.cap = cv2.VideoCapture(self.camera_key)

#Define the codec and create VidepWriter object

self.fourcc = cv2.VideoWriter_fourcc(*"XVID")
self.out = cv2.VideoWriter("Output_Saved_Video.avi", self.fourcc, 20.0, (640,480))

while (self.cap.isOpened()):
self.ret, self.frame = self.cap.read()

if self.ret == True:
self.frame = cv2.flip(self.frame, 180)

#write the flipped frame
self.out.write(self.frame)

cv2.imshow(
"Window", self.frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break

# Release everything if job is finished
self.cap.release()
self.out.release()
cv2.destroyAllWindows()

def main():
obj = SaveVideo(
0)
obj.Save_Video()

if __name__ == "__main__":
main()


Comments