天天看點

pytorch自帶網絡_輕松學Pytorch 使用torchvision實作對象檢測

pytorch自帶網絡_輕松學Pytorch 使用torchvision實作對象檢測

點選上方藍字關注我們

微信公衆号:OpenCV學堂

關注擷取更多計算機視覺與深度學習知識

大家好,前面一篇文章介紹了torchvision的模型ResNet50實作圖像分類,這裡再給大家介紹一下如何使用torchvision自帶的對象檢測模型Faster-RCNN實作對象檢測。Torchvision自帶的對象檢測模型是基于COCO資料集訓練的,最小分辨率支援800, 最大支援1333的輸入圖像。

Faster-RCNN模型

Faster-RCNN模型的基礎網絡是ResNet50, ROI生成使用了RPN,加上頭部組成。圖示如下:

pytorch自帶網絡_輕松學Pytorch 使用torchvision實作對象檢測

在torchvision架構下可以通過下面的代碼直接下載下傳預訓練模型,

model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)model.eval()
           

對模型使用GPU加速支援

# 使用GPU

train_on_gpu = torch.cuda.is_available()if train_on_gpu:     model.cuda()
           

推理輸出有三個資訊分别為:

boxes:表示對象框scores:表示每個對象得分labels:表示對于的分類标簽
           

圖像檢測

使用模型實作圖像檢測,支援90個類别的對象檢測,代碼實作如下:

def faster_rcnn_image_detection():

    image = cv.imread("D:/images/cars.jpg")

    blob = transform(image)

    c, h, w = blob.shape

    input_x = blob.view(1, c, h, w)

    output = model(input_x.cuda())[0]

    boxes = output['boxes'].cpu().detach().numpy()

    scores = output['scores'].cpu().detach().numpy()

    labels = output['labels'].cpu().detach().numpy()

    index = 0

    for x1, y1, x2, y2 in boxes:

        if scores[index] > 0.5:

            print(x1, y1, x2, y2)

            cv.rectangle(image, (np.int32(x1), np.int32(y1)),

                         (np.int32(x2), np.int32(y2)), (0, 255, 255), 1, 8, 0)

            label_id = labels[index]

            label_txt = coco_names[str(label_id)]

            cv.putText(image, label_txt, (np.int32(x1), np.int32(y1)), cv.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 255), 1)

        index += 1

    cv.imshow("Faster-RCNN Detection Demo", image)

    cv.waitKey(0)

    cv.destroyAllWindows()

運作結果下:

pytorch自帶網絡_輕松學Pytorch 使用torchvision實作對象檢測

視訊實時對象檢測

基于OpenCV實作視訊檔案或者攝像頭讀取,完成視訊的實時對象檢測,代碼實作如下:

1capture = cv.VideoCapture(
           

 運作結果如下:

pytorch自帶網絡_輕松學Pytorch 使用torchvision實作對象檢測

 推薦閱讀 

輕松學Pytorch–環境搭建與基本文法

Pytorch輕松學-建構淺層神經網絡

輕松學pytorch-建構卷積神經網絡

輕松學Pytorch –建構循環神經網絡

輕松學Pytorch-使用卷積神經網絡實作圖像分類

輕松學Pytorch-自定義資料集制作與使用

輕松學Pytorch-Pytorch可視化

輕松學Pytorch–Visdom可視化

輕松學Pytorch – 全局池化層詳解

輕松學Pytorch – 人臉五點landmark提取網絡訓練與使用

輕松學Pytorch – 年齡與性别預測

輕松學Pytorch –車輛類型與顔色識别

輕松學Pytorch-全卷積神經網絡實作表情識别

使用OpenVINO加速Pytorch表情識别模型

輕松學pytorch – 使用多标簽損失函數訓練卷積網絡

輕松學Pytorch-使用ResNet50實作圖像分類

志不強者智不達

言不信者行不果

pytorch自帶網絡_輕松學Pytorch 使用torchvision實作對象檢測

繼續閱讀