Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/Colorization/colorizeVideo.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 colorizeVideo.py --input greyscaleVideo.mp4
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 Video')
13
parser.add_argument('--input', help='Path to video file.')
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 video file.')
19
print('Usage example: python3 colorizeVideo.py --input greyscaleVideo.mp4')
20
exit()
21
22
if not os.path.isfile(args.input):
23
print('Input file does not exist')
24
exit()
25
26
print("Input video file: ", args.input)
27
28
# Read the input video
29
cap = cv.VideoCapture(args.input)
30
hasFrame, frame = cap.read()
31
32
outputFile = args.input[:-4] + '_colorized.avi'
33
vid_writer = cv.VideoWriter(outputFile, cv.VideoWriter_fourcc('M','J','P','G'), 60, (frame.shape[1],frame.shape[0]))
34
35
# Specify the paths for the 2 model files
36
protoFile = "./models/colorization_deploy_v2.prototxt"
37
weightsFile = "./models/colorization_release_v2.caffemodel"
38
39
# Load the cluster centers
40
pts_in_hull = np.load('./pts_in_hull.npy')
41
42
# Read the network into Memory
43
net = cv.dnn.readNetFromCaffe(protoFile, weightsFile)
44
45
if args.device == "cpu":
46
net.setPreferableBackend(cv.dnn.DNN_TARGET_CPU)
47
print("Using CPU device")
48
elif args.device == "gpu":
49
net.setPreferableBackend(cv.dnn.DNN_BACKEND_CUDA)
50
net.setPreferableTarget(cv.dnn.DNN_TARGET_CUDA)
51
print("Using GPU device")
52
53
# populate cluster centers as 1x1 convolution kernel
54
pts_in_hull = pts_in_hull.transpose().reshape(2, 313, 1, 1)
55
net.getLayer(net.getLayerId('class8_ab')).blobs = [pts_in_hull.astype(np.float32)]
56
net.getLayer(net.getLayerId('conv8_313_rh')).blobs = [np.full([1, 313], 2.606, np.float32)]
57
58
# from opencv sample
59
W_in = 224
60
H_in = 224
61
62
timer = []
63
64
while cv.waitKey(1):
65
66
hasFrame, frame = cap.read()
67
frameCopy = np.copy(frame)
68
if not hasFrame:
69
break
70
71
start = time.time()
72
73
img_rgb = (frame[:, :, [2, 1, 0]] * 1.0 / 255).astype(np.float32)
74
img_lab = cv.cvtColor(img_rgb, cv.COLOR_RGB2Lab)
75
img_l = img_lab[:, :, 0] # pull out L channel
76
77
# resize lightness channel to network input size
78
img_l_rs = cv.resize(img_l, (W_in, H_in))
79
img_l_rs -= 50 # subtract 50 for mean-centering
80
81
net.setInput(cv.dnn.blobFromImage(img_l_rs))
82
ab_dec = net.forward()[0, :, :, :].transpose((1, 2, 0)) # this is our result
83
84
(H_orig,W_orig) = img_rgb.shape[:2] # original image size
85
ab_dec_us = cv.resize(ab_dec, (W_orig, H_orig))
86
img_lab_out = np.concatenate((img_l[:, :, np.newaxis], ab_dec_us), axis=2) # concatenate with original L channel
87
img_bgr_out = np.clip(cv.cvtColor(img_lab_out, cv.COLOR_Lab2BGR), 0, 1)
88
89
end = time.time()
90
timer.append(end - start)
91
92
vid_writer.write((img_bgr_out * 255).astype(np.uint8))
93
94
vid_writer.release()
95
96
print("Time taken : {:0.5f} secs".format(sum(timer)))
97
print('Colorized video saved as ' + outputFile)
98
print('Done !!!')
99
100
101