segmentation.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import cv2 as cv
  2. import argparse
  3. import numpy as np
  4. import sys
  5. from common import *
  6. backends = (cv.dnn.DNN_BACKEND_DEFAULT, cv.dnn.DNN_BACKEND_HALIDE, cv.dnn.DNN_BACKEND_INFERENCE_ENGINE, cv.dnn.DNN_BACKEND_OPENCV,
  7. cv.dnn.DNN_BACKEND_VKCOM, cv.dnn.DNN_BACKEND_CUDA)
  8. targets = (cv.dnn.DNN_TARGET_CPU, cv.dnn.DNN_TARGET_OPENCL, cv.dnn.DNN_TARGET_OPENCL_FP16, cv.dnn.DNN_TARGET_MYRIAD, cv.dnn.DNN_TARGET_HDDL,
  9. cv.dnn.DNN_TARGET_VULKAN, cv.dnn.DNN_TARGET_CUDA, cv.dnn.DNN_TARGET_CUDA_FP16)
  10. parser = argparse.ArgumentParser(add_help=False)
  11. parser.add_argument('--zoo', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'models.yml'),
  12. help='An optional path to file with preprocessing parameters.')
  13. parser.add_argument('--input', help='Path to input image or video file. Skip this argument to capture frames from a camera.')
  14. parser.add_argument('--framework', choices=['caffe', 'tensorflow', 'torch', 'darknet'],
  15. help='Optional name of an origin framework of the model. '
  16. 'Detect it automatically if it does not set.')
  17. parser.add_argument('--colors', help='Optional path to a text file with colors for an every class. '
  18. 'An every color is represented with three values from 0 to 255 in BGR channels order.')
  19. parser.add_argument('--backend', choices=backends, default=cv.dnn.DNN_BACKEND_DEFAULT, type=int,
  20. help="Choose one of computation backends: "
  21. "%d: automatically (by default), "
  22. "%d: Halide language (http://halide-lang.org/), "
  23. "%d: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), "
  24. "%d: OpenCV implementation, "
  25. "%d: VKCOM, "
  26. "%d: CUDA"% backends)
  27. parser.add_argument('--target', choices=targets, default=cv.dnn.DNN_TARGET_CPU, type=int,
  28. help='Choose one of target computation devices: '
  29. '%d: CPU target (by default), '
  30. '%d: OpenCL, '
  31. '%d: OpenCL fp16 (half-float precision), '
  32. '%d: NCS2 VPU, '
  33. '%d: HDDL VPU, '
  34. '%d: Vulkan, '
  35. '%d: CUDA, '
  36. '%d: CUDA fp16 (half-float preprocess)'% targets)
  37. args, _ = parser.parse_known_args()
  38. add_preproc_args(args.zoo, parser, 'segmentation')
  39. parser = argparse.ArgumentParser(parents=[parser],
  40. description='Use this script to run semantic segmentation deep learning networks using OpenCV.',
  41. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  42. args = parser.parse_args()
  43. args.model = findFile(args.model)
  44. args.config = findFile(args.config)
  45. args.classes = findFile(args.classes)
  46. np.random.seed(324)
  47. # Load names of classes
  48. classes = None
  49. if args.classes:
  50. with open(args.classes, 'rt') as f:
  51. classes = f.read().rstrip('\n').split('\n')
  52. # Load colors
  53. colors = None
  54. if args.colors:
  55. with open(args.colors, 'rt') as f:
  56. colors = [np.array(color.split(' '), np.uint8) for color in f.read().rstrip('\n').split('\n')]
  57. legend = None
  58. def showLegend(classes):
  59. global legend
  60. if not classes is None and legend is None:
  61. blockHeight = 30
  62. assert(len(classes) == len(colors))
  63. legend = np.zeros((blockHeight * len(colors), 200, 3), np.uint8)
  64. for i in range(len(classes)):
  65. block = legend[i * blockHeight:(i + 1) * blockHeight]
  66. block[:,:] = colors[i]
  67. cv.putText(block, classes[i], (0, blockHeight//2), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))
  68. cv.namedWindow('Legend', cv.WINDOW_NORMAL)
  69. cv.imshow('Legend', legend)
  70. classes = None
  71. # Load a network
  72. net = cv.dnn.readNet(args.model, args.config, args.framework)
  73. net.setPreferableBackend(args.backend)
  74. net.setPreferableTarget(args.target)
  75. winName = 'Deep learning semantic segmentation in OpenCV'
  76. cv.namedWindow(winName, cv.WINDOW_NORMAL)
  77. cap = cv.VideoCapture(args.input if args.input else 0)
  78. legend = None
  79. while cv.waitKey(1) < 0:
  80. hasFrame, frame = cap.read()
  81. if not hasFrame:
  82. cv.waitKey()
  83. break
  84. frameHeight = frame.shape[0]
  85. frameWidth = frame.shape[1]
  86. # Create a 4D blob from a frame.
  87. inpWidth = args.width if args.width else frameWidth
  88. inpHeight = args.height if args.height else frameHeight
  89. blob = cv.dnn.blobFromImage(frame, args.scale, (inpWidth, inpHeight), args.mean, args.rgb, crop=False)
  90. # Run a model
  91. net.setInput(blob)
  92. score = net.forward()
  93. numClasses = score.shape[1]
  94. height = score.shape[2]
  95. width = score.shape[3]
  96. # Draw segmentation
  97. if not colors:
  98. # Generate colors
  99. colors = [np.array([0, 0, 0], np.uint8)]
  100. for i in range(1, numClasses):
  101. colors.append((colors[i - 1] + np.random.randint(0, 256, [3], np.uint8)) / 2)
  102. classIds = np.argmax(score[0], axis=0)
  103. segm = np.stack([colors[idx] for idx in classIds.flatten()])
  104. segm = segm.reshape(height, width, 3)
  105. segm = cv.resize(segm, (frameWidth, frameHeight), interpolation=cv.INTER_NEAREST)
  106. frame = (0.1 * frame + 0.9 * segm).astype(np.uint8)
  107. # Put efficiency information.
  108. t, _ = net.getPerfProfile()
  109. label = 'Inference time: %.2f ms' % (t * 1000.0 / cv.getTickFrequency())
  110. cv.putText(frame, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
  111. showLegend(classes)
  112. cv.imshow(winName, frame)