In this Python OpenCV article i want to show you how you can do Writing in To A Video, so for this you can watch my previous post on How To Read Mp4 Videos In Python OpenCV .
This is the complete source code for this article
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 48 49 50 |
import cv2 def main(): windowname = "Writing A Video" cv2.namedWindow(windowname) cap = cv2.VideoCapture('vid2.mp4') filename = "C:\\Users\\Parwiz\\Documents\\opencvvid\\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.releas() cap.release() if __name__ == "__main__": main() |
So in the above code first we have imported cv2 and after there are some lines of code that you can use for Reading Videos In OpenCV.
In these line of codes we are going to give name for our OpenCV window.
1 2 |
windowname = "Writing A Video" cv2.namedWindow(windowname) |
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('vid2.mp4') |
When we want to write a video in OpenCV we need to toil a bit harder. 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.
FourCC is 4-character code of codec used to compress the frames. For example, VideoWriter::fourcc(‘P’,’I’,’M’,’1′) is a MPEG-1 codec, VideoWriter::fourcc(‘M’,’J’,’P’,’G’) is a motion-jpeg codec etc. List of codes can be obtained at Video Codecs by FOURCC page. FFMPEG backend with MP4 container natively uses other values as fourcc code.
1 2 3 4 |
filename = "C:\Users\Parwiz\Documents\opencvvid\out.avi" codec = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D') framerate = 29 resolution = (640, 480) |
In here we have added our resolution and also frame rate.
1 |
VideoOutPut = cv2.VideoWriter(filename, codec, framerate, resolution) |
After that we are checking that if the capture is opened we are reading the frames.
1 2 3 4 5 6 7 8 9 |
if cap.isOpened(): ret, frame = cap.read() else: ret = False while ret: ret, frame = cap.read() |
Because we want to draw a circle in the recorder video so you can do like this
1 |
cv2.circle(frame, (200,200), 80, (0,255,0), -1) |
Run the code you will see the video
Also you can watch the complete video for this article
Subscribe and Get Free Video Courses & Articles in your Email