mask_rcnn.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. import cv2 as cv
  2. import argparse
  3. import numpy as np
  4. parser = argparse.ArgumentParser(description=
  5. 'Use this script to run Mask-RCNN object detection and semantic '
  6. 'segmentation network from TensorFlow Object Detection API.')
  7. parser.add_argument('--input', help='Path to input image or video file. Skip this argument to capture frames from a camera.')
  8. parser.add_argument('--model', required=True, help='Path to a .pb file with weights.')
  9. parser.add_argument('--config', required=True, help='Path to a .pxtxt file contains network configuration.')
  10. parser.add_argument('--classes', help='Optional path to a text file with names of classes.')
  11. parser.add_argument('--colors', help='Optional path to a text file with colors for an every class. '
  12. 'An every color is represented with three values from 0 to 255 in BGR channels order.')
  13. parser.add_argument('--width', type=int, default=800,
  14. help='Preprocess input image by resizing to a specific width.')
  15. parser.add_argument('--height', type=int, default=800,
  16. help='Preprocess input image by resizing to a specific height.')
  17. parser.add_argument('--thr', type=float, default=0.5, help='Confidence threshold')
  18. args = parser.parse_args()
  19. np.random.seed(324)
  20. # Load names of classes
  21. classes = None
  22. if args.classes:
  23. with open(args.classes, 'rt') as f:
  24. classes = f.read().rstrip('\n').split('\n')
  25. # Load colors
  26. colors = None
  27. if args.colors:
  28. with open(args.colors, 'rt') as f:
  29. colors = [np.array(color.split(' '), np.uint8) for color in f.read().rstrip('\n').split('\n')]
  30. legend = None
  31. def showLegend(classes):
  32. global legend
  33. if not classes is None and legend is None:
  34. blockHeight = 30
  35. assert(len(classes) == len(colors))
  36. legend = np.zeros((blockHeight * len(colors), 200, 3), np.uint8)
  37. for i in range(len(classes)):
  38. block = legend[i * blockHeight:(i + 1) * blockHeight]
  39. block[:,:] = colors[i]
  40. cv.putText(block, classes[i], (0, blockHeight//2), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))
  41. cv.namedWindow('Legend', cv.WINDOW_NORMAL)
  42. cv.imshow('Legend', legend)
  43. classes = None
  44. def drawBox(frame, classId, conf, left, top, right, bottom):
  45. # Draw a bounding box.
  46. cv.rectangle(frame, (left, top), (right, bottom), (0, 255, 0))
  47. label = '%.2f' % conf
  48. # Print a label of class.
  49. if classes:
  50. assert(classId < len(classes))
  51. label = '%s: %s' % (classes[classId], label)
  52. labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)
  53. top = max(top, labelSize[1])
  54. cv.rectangle(frame, (left, top - labelSize[1]), (left + labelSize[0], top + baseLine), (255, 255, 255), cv.FILLED)
  55. cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
  56. # Load a network
  57. net = cv.dnn.readNet(cv.samples.findFile(args.model), cv.samples.findFile(args.config))
  58. net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
  59. winName = 'Mask-RCNN in OpenCV'
  60. cv.namedWindow(winName, cv.WINDOW_NORMAL)
  61. cap = cv.VideoCapture(cv.samples.findFileOrKeep(args.input) if args.input else 0)
  62. legend = None
  63. while cv.waitKey(1) < 0:
  64. hasFrame, frame = cap.read()
  65. if not hasFrame:
  66. cv.waitKey()
  67. break
  68. frameH = frame.shape[0]
  69. frameW = frame.shape[1]
  70. # Create a 4D blob from a frame.
  71. blob = cv.dnn.blobFromImage(frame, size=(args.width, args.height), swapRB=True, crop=False)
  72. # Run a model
  73. net.setInput(blob)
  74. boxes, masks = net.forward(['detection_out_final', 'detection_masks'])
  75. numClasses = masks.shape[1]
  76. numDetections = boxes.shape[2]
  77. # Draw segmentation
  78. if not colors:
  79. # Generate colors
  80. colors = [np.array([0, 0, 0], np.uint8)]
  81. for i in range(1, numClasses + 1):
  82. colors.append((colors[i - 1] + np.random.randint(0, 256, [3], np.uint8)) / 2)
  83. del colors[0]
  84. boxesToDraw = []
  85. for i in range(numDetections):
  86. box = boxes[0, 0, i]
  87. mask = masks[i]
  88. score = box[2]
  89. if score > args.thr:
  90. classId = int(box[1])
  91. left = int(frameW * box[3])
  92. top = int(frameH * box[4])
  93. right = int(frameW * box[5])
  94. bottom = int(frameH * box[6])
  95. left = max(0, min(left, frameW - 1))
  96. top = max(0, min(top, frameH - 1))
  97. right = max(0, min(right, frameW - 1))
  98. bottom = max(0, min(bottom, frameH - 1))
  99. boxesToDraw.append([frame, classId, score, left, top, right, bottom])
  100. classMask = mask[classId]
  101. classMask = cv.resize(classMask, (right - left + 1, bottom - top + 1))
  102. mask = (classMask > 0.5)
  103. roi = frame[top:bottom+1, left:right+1][mask]
  104. frame[top:bottom+1, left:right+1][mask] = (0.7 * colors[classId] + 0.3 * roi).astype(np.uint8)
  105. for box in boxesToDraw:
  106. drawBox(*box)
  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)