欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入我们的社群。

OpenCV中使用Mask R-CNN进行实例分割

OpenCV 迷途小书童 4年前 (2020-11-26) 3732次浏览 0个评论

软硬兼环境

  • windows 10 64bit
  • nivdia gtx 1066
  • opencv 4.4.0

简介

Mask R-CNN 是在原有的 R-CNN 基础上实现了区域 ROI 的像素级别分割。tensorflow 框架有个扩展模块叫做 models,里面包含了很多预训练的网络模型,提供给开发者直接使用或者迁移学习使用,tensorflow object detection model zone 中现在有四个使用不同骨干网(InceptionV2ResNet50ResNet101Inception-ResnetV2)的 Mask R-CNN 模型,这些模型都是在 MSCOCO 数据集上训练出来的,其中使用 Inception 的模型是这四个中最快的,本文也是使用该模型。

模型下载

首先需要下载 Mask R-CNN 网络模型,地址是: http://download.tensorflow.org/models/object_detection/mask_rcnn_inception_v2_coco_2018_01_28.tar.gz, 下载后解压出里面的模型文件 frozen_inference_graph.pb

代码示例

  1. import cv2 as cv
  2. import argparse
  3. import numpy as np
  4. import os.path
  5. import sys
  6. import random
  7. # 设置目标检测的置信度阈值和Mask二值化分割阈值
  8. confThreshold = 0.5
  9. maskThreshold = 0.3
  10. parser = argparse.ArgumentParser(description='Use this script to run Mask-RCNN object detection and segmentation')
  11. parser.add_argument('--image', help='Path to image file')
  12. parser.add_argument('--video', help='Path to video file.')
  13. args = parser.parse_args()
  14. # 画bounding box
  15. def drawBox(frame, classId, conf, left, top, right, bottom, classMask):
  16. # Draw a bounding box.
  17. cv.rectangle(frame, (left, top), (right, bottom), (255, 178, 50), 3)
  18. label = '%.2f' % conf
  19. if classes:
  20. assert (classId < len(classes))
  21. label = '%s:%s' % (classes[classId], label)
  22. # Display the label at the top of the bounding box
  23. labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)
  24. top = max(top, labelSize[1])
  25. cv.rectangle(frame, (left, top - round(1.5 * labelSize[1])), (left + round(1.5 * labelSize[0]), top + baseLine),
  26. (255, 255, 255), cv.FILLED)
  27. cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 0), 1)
  28. # Resize the mask, threshold, color and apply it on the image
  29. classMask = cv.resize(classMask, (right - left + 1, bottom - top + 1))
  30. mask = (classMask > maskThreshold)
  31. roi = frame[top:bottom + 1, left:right + 1][mask]
  32. # color = colors[classId%len(colors)]
  33. # Comment the above line and uncomment the two lines below to generate different instance colors
  34. colorIndex = random.randint(0, len(colors) - 1)
  35. color = colors[colorIndex]
  36. frame[top:bottom + 1, left:right + 1][mask] = ([0.3 * color[0], 0.3 * color[1], 0.3 * color[2]] + 0.7 * roi).astype(
  37. np.uint8)
  38. # Draw the contours on the image
  39. mask = mask.astype(np.uint8)
  40. contours, hierarchy = cv.findContours(mask, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
  41. cv.drawContours(frame[top:bottom + 1, left:right + 1], contours, -1, color, 3, cv.LINE_8, hierarchy, 100)
  42. # For each frame, extract the bounding box and mask for each detected object
  43. def postprocess(boxes, masks):
  44. # Output size of masks is NxCxHxW where
  45. # N - number of detected boxes
  46. # C - number of classes (excluding background)
  47. # HxW - segmentation shape
  48. numClasses = masks.shape[1]
  49. numDetections = boxes.shape[2]
  50. frameH = frame.shape[0]
  51. frameW = frame.shape[1]
  52. for i in range(numDetections):
  53. box = boxes[0, 0, i]
  54. mask = masks[i]
  55. score = box[2]
  56. if score > confThreshold:
  57. classId = int(box[1])
  58. # Extract the bounding box
  59. left = int(frameW * box[3])
  60. top = int(frameH * box[4])
  61. right = int(frameW * box[5])
  62. bottom = int(frameH * box[6])
  63. left = max(0, min(left, frameW - 1))
  64. top = max(0, min(top, frameH - 1))
  65. right = max(0, min(right, frameW - 1))
  66. bottom = max(0, min(bottom, frameH - 1))
  67. # Extract the mask for the object
  68. classMask = mask[classId]
  69. # Draw bounding box, colorize and show the mask on the image
  70. drawBox(frame, classId, score, left, top, right, bottom, classMask)
  71. # mscoco_labels.names包含MSCOCO所有标注对象的类名称,共80个类别
  72. classesFile = "mscoco_labels.names"
  73. classes = None
  74. with open(classesFile, 'rt') as f:
  75. classes = f.read().rstrip('\n').split('\n')
  76. # 定义如何加载模型权重
  77. textGraph = "./mask_rcnn_inception_v2_coco_2018_01_28.pbtxt"
  78. # 模型权重
  79. modelWeights = "./frozen_inference_graph.pb"
  80. # 使用dnn模块加载模型
  81. net = cv.dnn.readNetFromTensorflow(modelWeights, textGraph)
  82. # 可以使用GPU或者CPU进行推断
  83. net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
  84. net.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)
  85. # colors.txt是在图像上标出实例时,所属类显示的颜色值
  86. colorsFile = "colors.txt";
  87. with open(colorsFile, 'rt') as f:
  88. colorsStr = f.read().rstrip('\n').split('\n')
  89. colors = [] # [0,0,0]
  90. for i in range(len(colorsStr)):
  91. rgb = colorsStr[i].split(' ')
  92. color = np.array([float(rgb[0]), float(rgb[1]), float(rgb[2])])
  93. colors.append(color)
  94. winName = 'Mask-RCNN Object detection and Segmentation in OpenCV'
  95. cv.namedWindow(winName, cv.WINDOW_NORMAL)
  96. # 处理后的结果保存到视频中
  97. outputFile = "mask_rcnn_out.avi"
  98. if (args.image):
  99. # Open the image file
  100. if not os.path.isfile(args.image):
  101. print("Input image file ", args.image, " doesn't exist")
  102. sys.exit(1)
  103. cap = cv.VideoCapture(args.image)
  104. outputFile = args.image[:-4] + '_mask_rcnn_out.jpg'
  105. elif (args.video):
  106. # Open the video file
  107. if not os.path.isfile(args.video):
  108. print("Input video file ", args.video, " doesn't exist")
  109. sys.exit(1)
  110. cap = cv.VideoCapture(args.video)
  111. outputFile = args.video[:-4] + '_mask_rcnn_out.avi'
  112. else:
  113. # Webcam input
  114. cap = cv.VideoCapture(0)
  115. # Get the video writer initialized to save the output video
  116. if (not args.image):
  117. vid_writer = cv.VideoWriter(outputFile, cv.VideoWriter_fourcc('M', 'J', 'P', 'G'), 28,
  118. (round(cap.get(cv.CAP_PROP_FRAME_WIDTH)), round(cap.get(cv.CAP_PROP_FRAME_HEIGHT))))
  119. while cv.waitKey(1) < 0:
  120. # 对每一帧数据进行处理
  121. hasFrame, frame = cap.read()
  122. # Stop the program if reached end of video
  123. if not hasFrame:
  124. print("Done processing !!!")
  125. print("Output file is stored as ", outputFile)
  126. cv.waitKey(3000)
  127. break
  128. # Create a 4D blob from a frame.
  129. blob = cv.dnn.blobFromImage(frame, swapRB=True, crop=False)
  130. # Set the input to the network
  131. net.setInput(blob)
  132. # 得到目标bounding box和mask
  133. boxes, masks = net.forward(['detection_out_final', 'detection_masks'])
  134. # Extract the bounding box and mask for each of the detected objects
  135. postprocess(boxes, masks)
  136. # Put efficiency information.
  137. t, _ = net.getPerfProfile()
  138. label = 'Inference time for a frame : %0.0f ms' % abs(
  139. t * 1000.0 / cv.getTickFrequency())
  140. cv.putText(frame, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
  141. # Write the frame with the detection boxes
  142. if (args.image):
  143. cv.imwrite(outputFile, frame.astype(np.uint8));
  144. else:
  145. vid_writer.write(frame.astype(np.uint8))
  146. cv.imshow(winName, frame)

上述代码同时支持图片和视频

  1. python demo.py --video test.mp4

opencv_mask_rcnn

OpenCV教程

https://xugaoxiang.com/category/ai/opencv/

喜欢 (1)

您必须 登录 才能发表评论!