【Pytorch神经网络实战案例】26 MaskR-CNN内置模型实现目标检测
生活随笔
收集整理的這篇文章主要介紹了
【Pytorch神经网络实战案例】26 MaskR-CNN内置模型实现目标检测
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 Pytorch中的目標檢測內置模型
在torchvision庫下的modelsldetecton目錄中,找到__int__.py文件。該文件中存放著可以導出的PyTorch內置的目標檢測模型。
2 MaskR-CNN內置模型實現目標檢測
2.1 代碼邏輯簡述
將COCO2017數據集上的預訓練模型maskrcnm_resnet50_fpn_coco加載到內存,并使用該模型對圖片進行目標檢測。
2.2 代碼實戰 :MaskR-CNN內置模型實現目標檢測
Maskrcnn_resent_Object Detection.py
from PIL import Image import matplotlib.pyplot as plt import torchvision.transforms as T import torchvision import numpy as np import cv2 import random import os os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'# 加載模型 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).convert('RGB') # 需要轉化:RuntimeError: The size of tensor a (4) must match the size of tensor b (3) at non-singletontransform = T.Compose([T.ToTensor()])img = transform(img)# MaskR - CNN模型會返回一個字典對象,該字典對象中包含如下key值:# boxes∶每個目標的邊框信息。# labels:每個目標的分類信息。# scores:每個目標的分類分值。# masks:每個目標的像素掩碼(Mask)。pred = model([img]) # 調用模型print('pred')print(pred)pred_score = list(pred[0]['scores'].detach().numpy())pred_t = [pred_score.index(x) for x in pred_score if x > threshold][-1]print("masks>0.5")print(pred[0]['masks'] > 0.5)masks = (pred[0]['masks'] > 0.5).squeeze().detach().cpu().numpy()print("this is masks")print(masks)pred_class = [COCO_INSTANCE_CATEGORY_NAMES[i] for i in list(pred[0]['labels'].numpy())]pred_boxes = [[(i[0], i[1]), (i[2], 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_classdef 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)randcol = colours[random.randrange(0, 10)]r[image == 1] = randcol[0]g[image == 1] = randcol[1]b[image == 1] = randcol[2]coloured_mask = np.stack([r, g, b], axis=2)print("randcol",randcol)return coloured_mask, randcoldef instance_segmentation_api(img_path, threshold=0.5, rect_th=3, text_size=3, text_th=5): # 進行目標檢測masks, boxes, pred_cls = get_prediction(img_path, threshold) # 調用模型print("已加載COCO標簽類數:", len(COCO_INSTANCE_CATEGORY_NAMES))img = cv2.imread(img_path)img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)for i in range(len(masks)):rgb_mask, randcol = random_colour_masks(masks[i]) # 使用隨機顏色為模型的掩碼區進行填充。img = cv2.addWeighted(img, 1, rgb_mask, 0.5, 0)# 元組里面有小數,需要轉化為整數 否則報錯T1,T2 = boxes[i][0],boxes[i][1]x1 = int(T1[0])y1 = int(T1[1])x2 = int(T2[0])y2 = int(T2[1])cv2.rectangle(img, (x1,y1), (x2,y2), color=randcol, thickness=rect_th)# # putText各參數依次是:圖片,添加的文字,左上角坐標,字體,字體大小,顏色黑,字體粗細cv2.putText(img, pred_cls[i], (x1,y1), cv2.FONT_HERSHEY_SIMPLEX, text_size, randcol, thickness=text_th)plt.figure(figsize=(20, 30))plt.imshow(img)plt.xticks([])plt.yticks([])plt.show()# 顯示模型結果 instance_segmentation_api('./models_2/mask.jpg')總結
以上是生活随笔為你收集整理的【Pytorch神经网络实战案例】26 MaskR-CNN内置模型实现目标检测的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Pytorch神经网络理论篇】 31
- 下一篇: Python带*参数和带**参数