Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/Colorization/colorizeImage.py
3119 views
1
# This code is written by Sunita Nayak at BigVision LLC. It is based on the OpenCV project.
2
# It is subject to the license terms in the LICENSE file found in this distribution and at http://opencv.org/license.html
3
4
# Usage example: python3 colorizeImage.py --input greyscaleImage.png
5
6
import numpy as np
7
import cv2 as cv
8
import argparse
9
import os.path
10
import time
11
12
parser = argparse.ArgumentParser(description='Colorize GreyScale Image')
13
parser.add_argument('--input', help='Path to image.')
14
parser.add_argument("--device", default="cpu", help="Device to inference on")
15
args = parser.parse_args()
16
17
if args.input is None:
18
print('Please give the input greyscale image name.')
19
print('Usage example: python3 colorizeImage.py --input greyscaleImage.png')
20
exit()
21
22
if not os.path.isfile(args.input):
23
print('Input file does not exist')
24
exit()
25
26
print("Input image file: ", args.input)
27
28
# Read the input image
29
frame = cv.imread(args.input)
30
31
# Specify the paths for the 2 model files
32
protoFile = "./models/colorization_deploy_v2.prototxt"
33
weightsFile = "./models/colorization_release_v2.caffemodel"
34
35
# Load the cluster centers
36
pts_in_hull = np.load('./pts_in_hull.npy')
37
38
# Read the network into Memory
39
net = cv.dnn.readNetFromCaffe(protoFile, weightsFile)
40
41
if args.device == "cpu":
42
net.setPreferableBackend(cv.dnn.DNN_TARGET_CPU)
43
print("Using CPU device")
44
elif args.device == "gpu":
45
net.setPreferableBackend(cv.dnn.DNN_BACKEND_CUDA)
46
net.setPreferableTarget(cv.dnn.DNN_TARGET_CUDA)
47
print("Using GPU device")
48
49
# populate cluster centers as 1x1 convolution kernel
50
pts_in_hull = pts_in_hull.transpose().reshape(2, 313, 1, 1)
51
net.getLayer(net.getLayerId('class8_ab')).blobs = [pts_in_hull.astype(np.float32)]
52
net.getLayer(net.getLayerId('conv8_313_rh')).blobs = [np.full([1, 313], 2.606, np.float32)]
53
54
# from opencv sample
55
W_in = 224
56
H_in = 224
57
58
start = time.time()
59
60
img_rgb = (frame[:, :, [2, 1, 0]] * 1.0 / 255).astype(np.float32)
61
img_lab = cv.cvtColor(img_rgb, cv.COLOR_RGB2Lab)
62
img_l = img_lab[:, :, 0] # pull out L channel
63
64
# resize lightness channel to network input size
65
img_l_rs = cv.resize(img_l, (W_in, H_in))
66
img_l_rs -= 50 # subtract 50 for mean-centering
67
68
net.setInput(cv.dnn.blobFromImage(img_l_rs))
69
ab_dec = net.forward()[0, :, :, :].transpose((1, 2, 0)) # this is our result
70
71
(H_orig, W_orig) = img_rgb.shape[:2] # original image size
72
ab_dec_us = cv.resize(ab_dec, (W_orig, H_orig))
73
img_lab_out = np.concatenate((img_l[:, :, np.newaxis],ab_dec_us), axis=2) # concatenate with original image L
74
img_bgr_out = np.clip(cv.cvtColor(img_lab_out, cv.COLOR_Lab2BGR), 0, 1)
75
76
end = time.time()
77
print("Time taken : {:0.5f} secs".format(end - start))
78
79
outputFile = args.input[:-4] + '_colorized.png'
80
cv.imwrite(outputFile, (img_bgr_out * 255).astype(np.uint8))
81
print('Colorized image saved as ' + outputFile)
82
print('Done !!!')
83
84
85