Artificial Intelligence 6 min read

Python Video Converter Using OpenCV: Convert Videos to Grayscale, Black‑White, and RGB

This article explains how to build a Python 3 video converter with OpenCV that reads an input video, optionally transforms each frame to grayscale, black‑and‑white, or RGB, and writes the result to a new output file, including command‑line argument parsing and dependency installation.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Video Converter Using OpenCV: Convert Videos to Grayscale, Black‑White, and RGB

Video converters allow users to change a video from one format to another; this guide demonstrates how to implement such a tool in Python 3 using the OpenCV4 library.

Project description : The converter reads a video file, optionally converts each frame to grayscale, black‑and‑white, or RGB, and saves the processed frames as a new video file.

Project code :

import cv2
import argparse

def convert_video(input_file, output_file, output_codec, gray=False, bw=False):
    # read the original video
    cap = cv2.VideoCapture(input_file)
    # set codec and get the size of frames
    fourcc = cv2.VideoWriter_fourcc(*output_codec)
    width = int(cap.get(3))
    height = int(cap.get(4))
    # create the output video writer
    out = cv2.VideoWriter(output_file, fourcc, 30, (width, height), True)
    while (cap.isOpened()):
        # read the frame
        ret, frame = cap.read()
        # check if end of the video
        if not ret:
            break
        # convert to gray
        if gray:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        # convert to black and white
        if bw:
            _, frame = cv2.threshold(frame, 127, 255, cv2.THRESH_BINARY)
        # convert to RGB
        if not gray and not bw:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        # write the frame to output video
        out.write(frame)
        # display the frame
        cv2.imshow('frame', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    # release the video capture and writer
    cap.release()
    out.release()
    # close all windows
    cv2.destroyAllWindows()

Project dependencies : Install OpenCV with pip install opencv-python .

The conversion process reads the original video, sets the codec, obtains frame dimensions, creates a writer, processes each frame according to the selected mode, writes the processed frame, and finally releases resources.

Argument parsing (optional):

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required=True, help="path to input video")
ap.add_argument("-o", "--output", required=True, help="path to output video")
ap.add_argument("-c", "--codec", required=True, help="codec of output video")
ap.add_argument("-g", "--gray", action="store_true", help="convert video to gray")
ap.add_argument("-b", "--bw", action="store_true", help="convert video to black-and-white")
args = vars(ap.parse_args())
convert_video(args["input"], args["output"], args["codec"], args["gray"], args["bw"])

Key parameters:

--input and --output specify the input and output video file paths.

--codec defines the codec name for the output video (e.g., "H.264").

These arguments enable running the script directly from the command line, controlling the conversion mode.

Project summary : The video format converter is a useful utility that simplifies changing video files between formats; using Python 3 and OpenCV makes implementation straightforward and saves time when handling video format conversions.

computer visionPythonvideo processingopencvvideo conversion
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.