Converting Color video to grayscale using OpenCV in Python

OpenCV is a huge open-source library for computer vision, machine learning, and image processing. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will see how to convert a colored video to a gray-scale format.

Approach:

  1. Import the cv2 module.
  2. Read the video file to be converted using the cv2.VideoCapture() method.
  3. Run an infinite loop.
  4. Inside the loop extract the frames of the video using the read() method.
  5. Pass the frame to the cv2.cvtColor() method with cv2.COLOR_BGR2GRAY as a parameter to convert it into gray-scale.
  6. Display the frame using the cv2.imshow() method.

Example: Suppose we have the video file CountdownTimer.mov as the input.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing the module
import cv2
  
# reading the vedio
source = cv2.VideoCapture('Countdown Timer.mov')
  
# running the loop
while True:
  
    # extracting the frames
    ret, img = source.read()
      
    # converting to gray-scale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  
    # displaying the video
    cv2.imshow("Live", gray)
  
    # exiting the loop
    key = cv2.waitKey(1)
    if key == ord("q"):
        break
      
# closing the window
cv2.destroyAllWindows()
source.release()

chevron_right


Output:

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.