• 基于PyTorch搭建Mask-RCNN实现实例分割


    基于PyTorch搭建Mask-RCNN实现实例分割

    在这篇文章中,我们将讨论 Mask RCNN Pytorch 背后的理论以及如何在 PyTorch 中使用预训练的 Mask R-CNN 模型。

    1. 语义分割、目标检测和实例分割

    在之前的博客文章里介绍了语义分割和目标检测(如果感兴趣可以参考以下文章):

    1. 图像语义分割概述
    2. Pytorch实现图像语义分割(初体验)
    3. 基于PyTorch搭建FasterRCNN实现目标检测
    • 语义分割:为图像中的每个像素分配一个类标签(例如狗、猫、人、背景等)。
    • 目标检测:在对象检测中,我们为包含对象的边界框分配一个类标签。
    • 实例分割:将图像中的每个物体分割成独立的实例。

    2. Mask R-CNN 架构

    Mask R-CNN 的架构是 Faster R-CNN 的扩展。Faster R-CNN 架构具有以下组件

    • 卷积层:输入图像经过多个卷积层以创建特征图。
    • 区域生成网络(RPN:Region Proposal Network)。卷积层的输出用于训练网络,该网络提出包围对象的区域。
    • 分类器:相同的特征图也用于训练分类器,该分类器为框内的对象分配标签。

    Faster R-CNN 比 Fast R-CNN 更快,因为特征图计算一次并由 RPN 和分类器重复使用。

    Mask R-CNN 将这一想法更进一步。除了将特征图提供给 RPN 和分类器之外,它还用它来预测边界框内对象的二进制掩码。

    看待 Mask R-CNN 的掩模预测部分的一种方式是,它是一个用于语义分割的全卷积网络(FCN)。唯一的区别是 FCN 应用于边界框,并且它与 RPN 和分类器共享卷积层。

    3. 基于PyTorch搭建Mask R-CNN

    3.1 输入和输出

    该模型期望输入是形状为 (n, c , h, w) 的张量图像列表,其值范围为 0-1。图像的大小不需要固定。

    • n 是图像数
    • c 是通道数,对于 RGB 图像,为 3
    • h 是图像的高度
    • w 是图像的宽度

    该模型返回边界框的坐标、模型预测将出现在输入图像中的类标签、标签的分数、标签中存在的每个类的掩码。

    3.2 预训练模型

    model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)
    model.eval()
    
    • 1
    • 2

    3.3 模型预测

    实例分割的标签列表与对象检测任务相同。

    COCO_INSTANCE_CATEGORY_NAMES = [
        '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
        'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
        'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
        'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A',
        'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
        'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
        'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
        'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
        'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table',
        'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
        'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',
        'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'
    ]
    
    
    def get_prediction(img_path, threshold):
        img = Image.open(img_path)
        transform = T.Compose([T.ToTensor()])
        img = transform(img)
        pred = model([img])
        pred_score = list(pred[0]['scores'].detach().numpy())
        pred_t = [pred_score.index(x) for x in pred_score if x > threshold][-1]
        masks = (pred[0]['masks'] > 0.5).squeeze().detach().cpu().numpy()
        pred_class = [COCO_INSTANCE_CATEGORY_NAMES[i] for i in list(pred[0]['labels'].numpy())]
        pred_boxes = [[(int(i[0]), int(i[1])), (int(i[2]), int(i[3]))] for i in list(pred[0]['boxes'].detach().numpy())]
        masks = masks[:pred_t + 1]
        pred_boxes = pred_boxes[:pred_t + 1]
        pred_class = pred_class[:pred_t + 1]
        return masks, pred_boxes, pred_class
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 从图像路径获得图像
    • 使用 PyTorch 的变换将图像转换为图像张量
    • 图像通过模型来获取预测
    • 从模型中获取掩模、预测类和边界框坐标,并将软掩模制成二进制(0或1)。示例:猫的部分设为 1,图像的其余部分设为 0。

    每个预测对象的蒙版都会从一组 11 种预定义颜色中随机获得颜色,以便在输入图像上可视化蒙版。

    def random_colour_masks(image):
        colours = [[0, 255, 0],[0, 0, 255],[255, 0, 0],[0, 255, 255],[255, 255, 0],[255, 0, 255],[80, 70, 180],[250, 80, 190],[245, 145, 50],[70, 150, 250],[50, 190, 190]]
        r = np.zeros_like(image).astype(np.uint8)
        g = np.zeros_like(image).astype(np.uint8)
        b = np.zeros_like(image).astype(np.uint8)
        r[image == 1], g[image == 1], b[image == 1] = colours[random.randrange(0, 10)]
        coloured_mask = np.stack([r, g, b], axis=2)
        return coloured_mask
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3.4 实例分割

    def instance_segmentation_api(img_path, threshold=0.5, rect_th=3, text_size=3, text_th=3):
        masks, boxes, pred_cls = get_prediction(img_path, threshold)
        img = cv2.imread(img_path)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        for i in range(len(masks)):
            rgb_mask = random_colour_masks(masks[i])
            img = cv2.addWeighted(img, 1, rgb_mask, 0.5, 0)
            cv2.rectangle(img, boxes[i][0], boxes[i][1],color=(0, 255, 0), thickness=rect_th)
            cv2.putText(img,pred_cls[i], boxes[i][0], cv2.FONT_HERSHEY_SIMPLEX, text_size, (0, 255, 0), thickness=text_th)
            plt.figure(figsize=(20,30))
            plt.imshow(img)
            plt.xticks([])
            plt.yticks([])
            plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 掩码、预测类和边界框通过 get_prediction 获得。
    • 每个蒙版都从 11 种颜色中随机选择一种颜色。
    • 使用 OpenCV 将每个掩模以 1:0.5 的比例添加到图像中。
    • 使用 cv2.rectangle 绘制边界框,并将类名注释为文本。
      显示最终输出

    3.5 运行测试

    3.6 完整代码

    import random
    import torchvision
    from PIL import Image
    from torchvision import transforms as T
    import numpy as np
    import cv2
    from matplotlib import pyplot as plt
    
    model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)
    model.eval()
    
    COCO_INSTANCE_CATEGORY_NAMES = [
        '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
        'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
        'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
        'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A',
        'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
        'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
        'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
        'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
        'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table',
        'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
        'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',
        'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'
    ]
    
    
    def get_prediction(img_path, threshold):
        img = Image.open(img_path)
        transform = T.Compose([T.ToTensor()])
        img = transform(img)
        pred = model([img])
        pred_score = list(pred[0]['scores'].detach().numpy())
        pred_t = [pred_score.index(x) for x in pred_score if x > threshold][-1]
        masks = (pred[0]['masks'] > 0.5).squeeze().detach().cpu().numpy()
        pred_class = [COCO_INSTANCE_CATEGORY_NAMES[i] for i in list(pred[0]['labels'].numpy())]
        pred_boxes = [[(int(i[0]), int(i[1])), (int(i[2]), int(i[3]))] for i in list(pred[0]['boxes'].detach().numpy())]
        masks = masks[:pred_t + 1]
        pred_boxes = pred_boxes[:pred_t + 1]
        pred_class = pred_class[:pred_t + 1]
        return masks, pred_boxes, pred_class
    
    
    def random_colour_masks(image):
        colours = [[0, 255, 0],[0, 0, 255],[255, 0, 0],[0, 255, 255],[255, 255, 0],[255, 0, 255],[80, 70, 180],[250, 80, 190],[245, 145, 50],[70, 150, 250],[50, 190, 190]]
        r = np.zeros_like(image).astype(np.uint8)
        g = np.zeros_like(image).astype(np.uint8)
        b = np.zeros_like(image).astype(np.uint8)
        r[image == 1], g[image == 1], b[image == 1] = colours[random.randrange(0, 10)]
        coloured_mask = np.stack([r, g, b], axis=2)
        return coloured_mask
    
    
    def instance_segmentation_api(img_path, threshold=0.5, rect_th=3, text_size=3, text_th=3):
        masks, boxes, pred_cls = get_prediction(img_path, threshold)
        img = cv2.imread(img_path)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        for i in range(len(masks)):
            rgb_mask = random_colour_masks(masks[i])
            img = cv2.addWeighted(img, 1, rgb_mask, 0.5, 0)
            cv2.rectangle(img, boxes[i][0], boxes[i][1],color=(0, 255, 0), thickness=rect_th)
            cv2.putText(img,pred_cls[i], boxes[i][0], cv2.FONT_HERSHEY_SIMPLEX, text_size, (0, 255, 0), thickness=text_th)
            plt.figure(figsize=(20,30))
            plt.imshow(img)
            plt.xticks([])
            plt.yticks([])
            plt.show()
    
    
    instance_segmentation_api('../img/cars.jpg')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
  • 相关阅读:
    武汉新时标文化传媒有限公司抖音小店运营技巧有哪些?
    Java练习题
    java计算机毕业设计springboot+vue留学服务管理平台系统(源码+系统+mysql数据库+Lw文档)
    水墨屏RFID超高频标签|RFID电子纸之组态软件操作说明2
    CNCC2023
    DigestUtils
    【图形学】14 UnityShader语义(二)
    React 开发一个移动端项目(1)
    单元测试llll
    Simulink|电动汽车、永磁电动机建模与仿真
  • 原文地址:https://blog.csdn.net/weixin_53065229/article/details/133028472