【ONNX】Faster-rcnn 转 ONNX

Faster RCNN代码可以参考下面链接:

https://github.com/facebookresearch/maskrcnn-benchmark

最后模型会保存为.pth格式,可以通过如下代码转为ONNX

import os
import numpy

from io import BytesIO

from matplotlib import pyplot

import requests
import torch
import timeit

from PIL import Image
from maskrcnn_benchmark.config import cfg
from predictor import COCODemo
from maskrcnn_benchmark.structures.image_list import ImageList

import pytorch_export_patch

if __name__ == "__main__":
    # load config from file and command-line arguments
    project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    cfg.merge_from_file(
        os.path.join(project_dir,
                     "configs/caffe2/e2e_faster_rcnn_R_50_FPN_1x_caffe2.yaml"))
    cfg.merge_from_list(["MODEL.DEVICE", "cpu"])
    cfg.freeze()

    # prepare object that handles inference plus adds predictions on top of image
    coco_demo = COCODemo(
        cfg,
        confidence_threshold=0.7,
        show_mask_heatmaps=False,
        masks_per_dim=2,
        min_image_size=480,
    )

    # prepare for onnx export
    coco_demo.model.prepare_onnx_export()


def single_image_to_top_predictions(image):
    image_list = ImageList(image.unsqueeze(0), [(int(image.size(-2)), int(image.size(-1)))])

    for param in coco_demo.model.parameters():
        param.requires_grad = False

    result, = coco_demo.model(image_list)
    scores = result.get_field("scores")
    result = (result.bbox, result.get_field('labels'), scores)
    return result


class FRCNNModel(torch.nn.Module):
    def forward(self, image):
        return single_image_to_top_predictions(image)


def fetch_image(url):
    response = requests.get(url)
    return Image.open(BytesIO(response.content)).convert("RGB")


if __name__ == '__main__':
    pil_image = fetch_image(
        url="http://farm3.staticflickr.com/2469/3915380994_2e611b1779_z.jpg")

    """
    Preprocessing image.
    """
    # convert to BGR format
    image = torch.from_numpy(numpy.array(pil_image)[:, :, [2, 1, 0]])
    original_image = image
    image = torch.nn.functional.upsample(image.permute(2, 0, 1).unsqueeze(0).to(torch.float), size=(960, 1280)).to(torch.uint8).squeeze(0).permute(1, 2, 0).to('cpu')

    image = image.permute(2, 0, 1)

    if not cfg.INPUT.TO_BGR255:
        image = image.float() / 255.0
        image = image[[2, 1, 0]]
    else:
        image = image.float()

    # we absolutely want fixed size (int) here (or we run into a tracing error (or bug?)
    # or we might later decide to make things work with variable size...
    image = image - torch.tensor(cfg.INPUT.PIXEL_MEAN)[:, None, None].to('cpu')

    model_path = 'faster_rcnn_R_50_FPN_1x.onnx'

    with torch.no_grad():
        model = FRCNNModel()
        model.eval()

        torch.onnx.export(model, (image,), model_path, verbose=True, opset_version=10, strip_doc_string=True, do_constant_folding=True)

        pytorch_export_patch.postprocess_model(model_path)

 参考:https://github.com/BowenBao/maskrcnn-benchmark/blob/onnx_stage/demo/export_to_onnx.py

Faster-RCNN是一种用于目标检测的深度学习网络模型。它是在R-CNN和Fast RCNN的基础上发展而来的,通过将特征抽取、proposal提取、bounding box regression和classification整合在一个网络中,提高了综合性能和检测速度。[2] Faster-RCNN训练过程可以分为以下几个步骤: 1. 使用一个预训练的卷积神经网络(如VGG16)来提取图像的特征。 2. 在特征图上使用Region Proposal Network (RPN) 来生成候选目标框(proposals)。 3. 使用这些候选目标框和真实标签来计算损失函数,并通过反向传播来更新网络参数,以使网络能够更好地预测目标框的位置和类别。 4. 使用训练好的RPN来生成候选目标框,并将这些候选目标框输入到网络中进行分类和边界框回归。 5. 通过计算损失函数并反向传播来更新网络参数,以进一步提高检测性能。 6. 可以进行多次迭代的训练,每次迭代都使用之前训练好的网络来初始化网络参数,并继续训练网络。[3] Faster-RCNN的网络结构包括一个共享的卷积层(用于特征提取)和两个分支:一个用于生成候选目标框的RPN,另一个用于对这些候选目标框进行分类和边界框回归。通过共享卷积层,Faster-RCNN能够在不同尺度的特征图上进行目标检测,从而提高检测的准确性和效率。[2] 总结来说,Faster-RCNN是一种用于目标检测的深度学习网络模型,通过整合特征抽取、proposal提取、bounding box regression和classification,提高了综合性能和检测速度。它的训练过程包括特征提取、候选目标框生成、分类和边界框回归等步骤。[2][3]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值