In this Python OpenCV lesson we are going to learn about Python OpenCV Writing to Video, basically we want to add a circle in our video.
This is the complete source code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import cv2 def main(): windowname = "Writing To A Video" cv2.namedWindow(windowname) cap = cv2.VideoCapture('myvidsample.mp4') filename = "out.avi" codec = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D') framerate = 29 resolution = (640, 480) VideoOutPut = cv2.VideoWriter(filename, codec, framerate, resolution) if cap.isOpened(): ret, frame = cap.read() else: ret = False while ret: ret, frame = cap.read() cv2.circle(frame, (200,200), 80, (0,255,0), -1) VideoOutPut.write(frame) cv2.imshow(windowname, frame) if cv2.waitKey(1) == 27: break cv2.destroyAllWindows() VideoOutPut.release() cap.release() if __name__ == "__main__": main() |
This section of code is for creating and reading from input file. If the input is a camera pass 0 instead of the video filename.
1 |
cap = cv2.VideoCapture('myvidsample.mp4') |
When we want to write a video in OpenCV we need some more works. We need to create a VideoWriter object. first, we should specify the output file name with its format (eg: output.avi). then, we should specify the FourCC code and the number of frames per second (FPS). Lastly, the frame size should be passed.
1 2 3 4 5 6 |
filename = "out.avi" codec = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D') framerate = 29 resolution = (640, 480) VideoOutPut = cv2.VideoWriter(filename, codec, framerate, resolution) |
We want to add a circle in the video, so this code is used for creating a circle.
1 |
cv2.circle(frame, (200,200), 80, (0,255,0), -1) |
Run the code and this is the result.