# Support files @ https://drive.google.com/drive/folders/1VftER_oapccpYpxhDOl0j_14CL0Z9Nvz?usp=sharing
# Libraries from: https://drive.google.com/drive/folders/1FaDajjtAsntF_Sw5gqF0WyakviA5l8-a
# Code from: https://www.codespeedy.com/automatic-colorization-of-black-and-white-images-using-ml-in-python/
import numpy as np
import cv2
prototxt = "colorization_deploy_v2.prototxt"
caffe_model = "colorization_release_v2.caffemodel"
pts_npy = "pts_in_hull.npy"
inputImage = "Cat.jpg"
outputImage = "CatColored.jpg"
net = cv2.dnn.readNetFromCaffe(prototxt, caffe_model) # Load model
pts = np.load(pts_npy)
layer1 = net.getLayerId("class8_ab")
layer2 = net.getLayerId("conv8_313_rh")
pts = pts.transpose().reshape(2, 313, 1, 1)
net.getLayer(layer1).blobs = [pts.astype("float32")]
net.getLayer(layer2).blobs = [np.full([1, 313], 2.606, dtype="float32")]
inputImage = cv2.imread(inputImage)
inputImage = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY) # To grayscale
inputImage = cv2.cvtColor(inputImage, cv2.COLOR_GRAY2RGB) # To RGB
cv2.imshow("GrayScale", inputImage)
# Converting the RGB image into LAB format
# Normalizing the image
normalized = inputImage.astype("float32") / 255.0
lab_image = cv2.cvtColor(normalized, cv2.COLOR_RGB2LAB) # To LAB format
resized = cv2.resize(lab_image, (224, 224))
L = cv2.split(resized)[0] # Extract value of L for LAB image
L -= 50
# Setting input
net.setInput(cv2.dnn.blobFromImage(L))
# Finding the values of 'a' and 'b'
ab = net.forward()[0, :, :, :].transpose((1, 2, 0))
ab = cv2.resize(ab, (inputImage.shape[1], inputImage.shape[0]))
# Combining L, a, and b channels
L = cv2.split(lab_image)[0]
LAB_colored = np.concatenate((L[:, :, np.newaxis], ab), axis=2)# Combining L,a,b
RGB_colored = cv2.cvtColor(LAB_colored,cv2.COLOR_LAB2RGB) # LAB to RGB
RGB_colored = np.clip(RGB_colored, 0, 1) # Limit values in array
# Changing pixel intensity back to [0,255] as we scaled during pre-processing and converted pixel intensity to [0,1]
RGB_colored = (255 * RGB_colored).astype("uint8")
RGB_BGR = cv2.cvtColor(RGB_colored, cv2.COLOR_RGB2BGR)
cv2.imshow("Colorized", RGB_BGR)
cv2.imwrite(outputImage, RGB_BGR)
No comments:
Post a Comment