colorizeVideo.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. # Usage example: python3 colorizeVideo.py --input greyscaleVideo.mp4
  4. import numpy as np
  5. import cv2 as cv
  6. import argparse
  7. import os.path
  8. import time
  9. parser = argparse.ArgumentParser(description='Colorize GreyScale Video')
  10. parser.add_argument('--input', help='Path to video file.')
  11. parser.add_argument("--device", default="cpu", help="Device to inference on")
  12. args = parser.parse_args()
  13. if args.input is None:
  14. print('Please give the input greyscale video file.')
  15. print('Usage example: python3 colorizeVideo.py --input greyscaleVideo.mp4')
  16. exit()
  17. if not os.path.isfile(args.input):
  18. print('Input file does not exist')
  19. exit()
  20. print("Input video file: ", args.input)
  21. # Read the input video
  22. cap = cv.VideoCapture(args.input)
  23. hasFrame, frame = cap.read()
  24. outputFile = args.input[:-4] + '_colorized.avi'
  25. vid_writer = cv.VideoWriter(outputFile, cv.VideoWriter_fourcc('M','J','P','G'), 60, (frame.shape[1],frame.shape[0]))
  26. # Specify the paths for the 2 model files
  27. protoFile = "./models/colorization_deploy_v2.prototxt"
  28. weightsFile = "./models/colorization_release_v2.caffemodel"
  29. # Load the cluster centers
  30. pts_in_hull = np.load('./pts_in_hull.npy')
  31. # Read the network into Memory
  32. net = cv.dnn.readNetFromCaffe(protoFile, weightsFile)
  33. if args.device == "cpu":
  34. net.setPreferableBackend(cv.dnn.DNN_TARGET_CPU)
  35. print("Using CPU device")
  36. elif args.device == "gpu":
  37. net.setPreferableBackend(cv.dnn.DNN_BACKEND_CUDA)
  38. net.setPreferableTarget(cv.dnn.DNN_TARGET_CUDA)
  39. print("Using GPU device")
  40. # populate cluster centers as 1x1 convolution kernel
  41. pts_in_hull = pts_in_hull.transpose().reshape(2, 313, 1, 1)
  42. net.getLayer(net.getLayerId('class8_ab')).blobs = [pts_in_hull.astype(np.float32)]
  43. net.getLayer(net.getLayerId('conv8_313_rh')).blobs = [np.full([1, 313], 2.606, np.float32)]
  44. # from opencv sample
  45. W_in = 224
  46. H_in = 224
  47. timer = []
  48. while cv.waitKey(1):
  49. hasFrame, frame = cap.read()
  50. frameCopy = np.copy(frame)
  51. if not hasFrame:
  52. break
  53. start = time.time()
  54. img_rgb = (frame[:, :, [2, 1, 0]] * 1.0 / 255).astype(np.float32)
  55. img_lab = cv.cvtColor(img_rgb, cv.COLOR_RGB2Lab)
  56. img_l = img_lab[:, :, 0] # pull out L channel
  57. # resize lightness channel to network input size
  58. img_l_rs = cv.resize(img_l, (W_in, H_in))
  59. img_l_rs -= 50 # subtract 50 for mean-centering
  60. net.setInput(cv.dnn.blobFromImage(img_l_rs))
  61. ab_dec = net.forward()[0, :, :, :].transpose((1, 2, 0)) # this is our result
  62. (H_orig,W_orig) = img_rgb.shape[:2] # original image size
  63. ab_dec_us = cv.resize(ab_dec, (W_orig, H_orig))
  64. img_lab_out = np.concatenate((img_l[:, :, np.newaxis], ab_dec_us), axis=2) # concatenate with original L channel
  65. img_bgr_out = np.clip(cv.cvtColor(img_lab_out, cv.COLOR_Lab2BGR), 0, 1)
  66. end = time.time()
  67. timer.append(end - start)
  68. vid_writer.write((img_bgr_out * 255).astype(np.uint8))
  69. vid_writer.release()
  70. print("Time taken : {:0.5f} secs".format(sum(timer)))
  71. print('Colorized video saved as ' + outputFile)
  72. print('Done !!!')