cv2 Mask-RCNN——实例分割框架

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/github_39611196/article/details/88077505

Mask R-CNN 是一个两阶段的框架,第一个阶段扫描图像并生成提议(proposals,即有可能包含一个目标的区域),第二阶段分类提议并生成边界框和掩码。Mask R-CNN 扩展自 Faster R-CNN,由同一作者在去年提出。Faster R-CNN 是一个流行的目标检测框架,Mask R-CNN 将其扩展为实例分割框架。

 下载权值文件:http://download.tensorflow.org/models/object_detection/mask_rcnn_inception_v2_coco_2018_01_28.tar.gz

下载后解压到项目根目录下即可。

示例代码:

import cv2
import numpy as np
import os.path
import sys
import random

# 初始化参数
confThreshold = 0.5  # 置信度阈值
maskThreshold = 0.3  # 掩码阈值

# 绘制预测的边界框,着色并在图像上显示蒙版
def drawBox(frame, classId, conf, left, top, right, bottom, classMask):
    # 绘制一个边界框
    cv2.rectangle(frame, (left, top), (right, bottom), (255, 178, 50), 3)
    
    # 输入类的标签值
    label = '%.2f' % conf
    if classes:
        assert(classId < len(classes))
        label = '%s:%s' % (classes[classId], label)
        
    # 在边界框的顶部显示标签值
    labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
    top = max(top, labelSize[1])
    
    cv2.rectangle(frame, (left, top - round(1.5 * labelSize[1])), (left + round(1.5 * labelSize[0]), top + baseLine), (255, 255, 255), cv2.FILLED)
    cv2.putText(frame, label, (left, top), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 0), 1)
    
    # 调整蒙版,阈值,颜色的大小并将其应用于图像
    classMask = cv2.resize(classMask, (right - left + 1, bottom - top + 1))
    mask = (classMask > maskThreshold)
    roi = frame[top: bottom + 1, left: right + 1][mask]
    
    # color = color[classId%len(colors)]
    # 注释上面的行并取消注释下面的两行以生成不同的实例颜色
    colorIndex = random.randint(0, len(colors) - 1)
    color = colors[colorIndex]
    
    frame[top: bottom + 1, left: right + 1][mask] = ([0.3 * color[0], 0.3 * color[1], 0.3 * color[2]] + 0.7 * roi).astype(np.uint8)
    
    # 在图像上绘制轮廓
    mask = mask.astype(np.uint8)
    im2, contours, hierachy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(frame[top: bottom + 1, left: right + 1], contours, -1, color, 3, cv2.LINE_8, hierachy, 100)


# 对于每个帧,提取每个检测到的对象的边界框和掩码
def postprocess(boxes, masks):
    # 掩模的输出大小为NxCxHxW
    # N  - 检测到的框数
    # C  - 课程数量(不包括背景)
    # HxW  - 分割形状
    numClasses = mask.shape[1]
    numDetections = boxes.shape[2]
    
    frameH = frame.shape[0]
    frameW = frame.shape[1]
    
    for i in range(numDetections):
        box = boxes[0, 0, i]
        mask = mask[i]
        score = box[2]
        if score > confThreshold:
            classId = int(box[1])
            
            # 提取边界框
            left = int(frameW * box[3])
            top = int(frameH * box[4])
            right = int(frameW * box[5])
            bottom = int(frameH * box[6])
            
            left = max(0, min(left, frameW - 1))
            top = max(0, min(top, frameH - 1))
            right = max(0, min(right, frameW - 1))
            bottom = max(0, min(bottom, frameH - 1))
            
            # 提取对象的掩码
            classMask = mask[classId]
            
            # 绘制边界框,着色并在图像上显示蒙版
            drawBox(frame, classId, score, left, top, right, bottom, classMask)


# 加载类的名称
classesFile = 'mscoco_labels.names'
classes = None
with open(classesFile, 'rt') as f:
    classes = f.read().rstrip('\n').split('\n')
    
# 为模型提供textGraph和weight文件
textGraph = 'mask_rcnn_inception_v2_coco_2018_01_28.pbtxt'
modelWeight = 'mask_rcnn_inception_v2_coco_2018_01_28/frozen_inference_graph.pb'

# 加载网络
net = cv2.dnn.readNetFromTensorflow(modelWeight, textGraph)
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)

# 加载类
colorsFile = 'colors.txt'
with open(colorsFile, 'rt') as f:
    colorsStr = f.read().rstrip('\n').split('\n')
colors = [] # [0, 0, 0]
for i in range(len(colorsStr)):
    rgb = colorsStr[i].split(' ')
    color = np.array([float(rgb[0]), float(rgb[1]), float(rgb[2])])
    colors.append(color)
    
winName = 'Mask-RCNN Object detction and Segmentation in OpenCV'
cv2.namedWindow(winName, cv2.WINDOW_NORMAL)

outputFile = 'mask_rcnn_out_py.avi'
# 打开视频文件
cap = cv2.VideoCapture('cars.mp4')

# 初始化视频编写器以保存输出视频
vid_writer = cv2.VideoWriter(outputFile, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 28, 
                            (round(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), round(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))))

while cv2.waitKey(1) < 0:
    # 获取视频帧
    hasFrame, frame = cap.read()
    
    # 如果到达视频结尾,停止该程序
    if not hasFrame:
        print('Done processing !!!')
        print('Output file is stored as ', outputFile)
        cv2.waitKey(3000)
        break
    
    # 从框架创建4D blob。
    blob = cv2.dnn.blobFromImage(frame, swapRB=True, crop=True)
    
    # 设置网络的输入
    net.setInput(blob)
    
    # 运行正向传递以从输出层获取输出
    boxes, masks = net.forward(['detection_out_final', 'detection_masks'])
    
    # 为每个检测到的对象提取边界框和蒙版
    postprocess(boxes, masks)
    
    # 提取效率信息
    t, _ = net.getPerfProfile()
    label = 'Mask-RCNN on 2.5 GHz Intel Core i7 CPU, Inference time for a frame : %0.0f ms' % abs(t * 1000.0 / cv.getTickFrequency())
    cv2.putText(frame, label, (0, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0,0))
    
    # 用检测框写入帧
    vid_writer.write(frame.astype(np.uint8))
    cv2.imshow(winName, frame)

猜你喜欢

转载自blog.csdn.net/github_39611196/article/details/88077505