Instagram
youtube
Facebook
Twitter

Read, Write, and Grayscale Videos

  • OpenCV is a powerful computer vision library for Video Processing.
     

  • OpenCV supports a wide variety of video formats, including AVI, MP4, and MPEG, and also supports capturing videos from cameras and webcams.

  • OpenCV's video reading functions can read frames from a video file and decode them into an image format.

  • We can implement various OpenCV functions on these decoded image formats.

 

In this tutorial, we’ll learn how to read and write videos in OpenCV.

Input:

 

Code:

import cv2
my_input = cv2.VideoCapture("video1.mp4")
if not my_input.isOpened():
    print("Error opening video file")
    exit()
fps = int(my_input.get(cv2.CAP_PROP_FPS))
width = int(my_input.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(my_input.get(cv2.CAP_PROP_FRAME_HEIGHT))
output_file = "output_video.mp4"
fourcc = cv2.VideoWriter_fourcc(*'mp4v') 
out = cv2.VideoWriter(output_file, fourcc, fps, (width, height), isColor = False)
while my_input.isOpened():
    ret, frame = my_input.read() 
    if ret:
        grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        out.write(grey)
        cv2.imshow("Frame", grey)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
my_input.release()
out.release()
cv2.destroyAllWindows()
  • First we imported OpenCV.

  • Then, we used the cv2.VideoCapture() function to read the video file. We can use cv2.VideoCapture(0) to capture video with the first webcam and cv2.VideoCapture(1) to capture video with a second webcam.

  • Then, we used cv2.isOpened() function to check if the video is opened or not. If not, then it prints an error message.

  • Then, we used the get() method to take the properties of the input video like fps, width, and height.

  • Then, we specifies the name of the output file and fourcc.

  • Then, we used cv2.videowriter() function to set the properties of the output video. We have used the properties of our input video.

  • Then, we used a while loop until the input video is opened.

  • Within the loop, we used the read() method with VideoCapture object to read a frame from the input video file and store it in the variable. The read() method returns a boolean value (ret) to indicate whether the frame was read successfully or not.

  • If the frame was read successfully, we have used the cv2.cvtcolor() to convert the frames into grayscale.

  • Then, we used the write() method to write the final video in videowriter object.

  • At last we used cv2.imshow to display the final result and .release() method to release the resources.

 

Result: