-
Run the following command line in the terminal:
pip install opencv-python opencv-contrib-python numpy
-
Enter the path of the black and white images in the code, also enter the output directory.
-
Download the following models and paste their path in the code:
a. colorization_deploy_v2.prototxt
-
Run the code and it will output a colour image
Image Input:
Image Output:
This script implements automatic colorization of black-and-white images using a pre-trained deep learning model in OpenCV. Below is a step-by-step breakdown:
- The script uses essential libraries:
numpy
for numerical computations.cv2
(OpenCV) for image processing.os
for file path management.
- Specifies the paths to the required model files:
prototxt
: Defines the network architecture.caffemodel
: Contains the pre-trained weights.npy
: Stores cluster centers for color distribution.
- Ensures paths are dynamically adjusted and checks the existence of critical files.
- Loads the pre-trained model (
.prototxt
and.caffemodel
) using OpenCV'scv2.dnn.readNetFromCaffe
. - Loads the color cluster centers from the
.npy
file. - Modifies the network by adding cluster centers as 1x1 convolutions.
- Input: Path to a black-and-white image.
- Steps:
- Reads the input image and verifies its existence.
- Converts the image to the LAB color space, where:
L
: Lightness (input channel for colorization).a
andb
: Color channels (predicted by the model).
- Preprocesses the image:
- Normalizes pixel values.
- Resizes the image to match the model input dimensions.
- Extracts and adjusts the
L
channel.
- Feeds the processed
L
channel to the network. - Predicts the
a
andb
channels and resizes them to the original image dimensions. - Combines the original
L
channel with the predicteda
andb
channels. - Converts the LAB image back to the BGR color space for display.
- Clamps pixel values to the valid range and converts the image to 8-bit format.
- Utilizes OpenCV's DNN module to load and process pre-trained deep learning models.
- Automatically converts and colorizes black-and-white images using the LAB color space.
- Provides robust error handling for missing files or invalid inputs.