Getting Started with OpenCV - Reversing a Video

Getting Started with OpenCV - Reversing a Video

The easiest project you can make using OpenCV

·

1 min read

OpenCV's documentation is the best place to learn OpenCV, check it out.

Learn the basics of Image and Video Handling and then try reversing a video by yourself. If you are stuck here is the code for your reference.

Make sure you are comfortable with Numpy before jumping on it OpenCV.


# Import the library 
import cv2 as cv

#Video Capture Instance
cap = cv.VideoCapture('videopath.mp4')

#Total number of frames in video
frames = cap.get(cv.CAP_PROP_FRAME_COUNT)

#Frames per second 
fps = cap.get(cv.CAP_PROP_FPS)

#height and width of video
height = cap.get(cv.CAP_PROP_FRAME_HEIGHT)
width = cap.get(cv.CAP_PROP_FRAME_WIDTH)

fourcc = cv.VideoWriter_fourcc(*'MJPG')
out = cv.VideoWriter('reversed_vid_name.avi', fourcc,fps ,(int(width*0.5), int(height*0.5)))

#We can print the progress of the video as it will take some time depending on video quality and length.
# print("No. of frames are : {}".format(frames))
# print("Frames per second is :{}".format(fps))

# We get the index of the last frame of the video file
frame_index = frames-1

if(cap.isOpened()):
    while(frame_index!=0):
        cap.set(cv.CAP_PROP_POS_FRAMES, frame_index)
        ret, frame = cap.read()
        frame = cv.resize(frame,(int(width*0.5), int(height*0.5)))

        #OPTIONAL : To show the reversing video
        #cv2.imshow('winname', frame)

        #Writing the reversed video 
        out.write(frame)
        #Decrementing Frame index at each step
        frame_index = frame_index-1

        #Printing the progress
        if(frame_index%100==0):
            print(frame_index)
        # if(cv2.waitKey(2)==ord('q')):
        #     break
out.release()
cap.release()