Faster RCNN Pytorch 實現 代碼級 詳解

基本結構:

采用VGG提取特征的Faster RCNN.

self.backbone:提取出特征圖->features

self.rpn:選出推薦框->proposals

self.roi heads:根據proposals在features上進行摳圖->detections

        
features = self.backbone(images.tensors)proposals, proposal_losses = self.rpn(images, features, targets)
detections, detector_losses = self.roi_heads(features, proposals, images.image_sizes, targets)

1.self.backbone

    def forward(self, x):identity = xout = self.conv1(x)out = self.bn1(out)out = self.relu(out)out = self.conv2(out)out = self.bn2(out)if self.downsample is not None:identity = self.downsample(x)out += identityout = self.relu(out)return out

這里pteaures就是提取的特征圖、而臺teaures是字思形式,由5張特征圖組成,這里就是構成了不同的尺度的要求,特征圖越小,所映射原圖的范圍越大。
注:這里的理解很重要,,其實這里能夠完全理解,那對圖像檢測基本就入門了,

五種featureMap:

[1,256,11,21]1:是pytorch四要求的一般會用于batchsize的功效,多少張圖片256:通道數
11:? height? 高

21:? weight? 寬

2.self.rpn

objectness, pred_bbox_deltas = self.head(features)
anchors = self.anchor_generator(images, features)boxes, scores = self.filter_proposals(proposals, objectness, images.image_sizes, num_anchors_per_level)

self.head(features):

    def forward(self, x):# type: (List[Tensor])logits = []bbox_reg = []for feature in x:t = F.relu(self.conv(feature))logits.append(self.cls_logits(t))  # 對t分類bbox_reg.append(self.bbox_pred(t))  # 對t回歸return logits, bbox_reg

x:就是輸出的5張特征圖features

objectness, pred_bbox_deltas = self.head(features)

錨框是由特征圖上一個像素點在原圖上得到的不同尺度的錨框,一般fasterrcnn論文里面是9個尺度
在這里是3

anchors = self.anchor_generator(images, features)

boxes, scores = self.filter_proposals(proposals, objectness, images.image_sizes, num_anchors_per_level)

這里的scores是的是前景的概率。(這里一般就是2分類,前景或背景)

top_n_idx = self._get_top_n_idx(objectness, num_anchors_per_level)

222603—》4693

 for boxes, scores, lvl, img_shape in zip(proposals, objectness, levels, image_shapes):boxes = box_ops.clip_boxes_to_image(boxes, img_shape)keep = box_ops.remove_small_boxes(boxes, self.min_size)boxes, scores, lvl = boxes[keep], scores[keep], lvl[keep]# non-maximum suppression, independently done per level# NMS的實現keep = box_ops.batched_nms(boxes, scores, lvl, self.nms_thresh)# keep only topk scoring predictions# keep就是最終保留的keep = keep[:self.post_nms_top_n()]boxes, scores = boxes[keep], scores[keep]final_boxes.append(boxes)final_scores.append(scores)return final_boxes, final_scores

4693–》1324

1324–》1000
這里的1000是在faster_rcnn.py中設置的

為什么不是2000是因為訓練的時候是2000,這里只是測試

proposals, proposal_losses = self.rpn(images, features, targets)

?roi_heads()

        box_features = self.box_roi_pool(features, proposals, image_shapes)box_features = self.box_head(box_features)class_logits, box_regression = self.box_predictor(box_features)#class_logits: 分類概率 和 box_regression :邊界框回歸

box_roi_pool 規整,為相同尺度的特征圖,便于之后的分類與回歸
box_roi_pool:兩個FC層

        detections, detector_losses = self.roi_heads(features, proposals, images.image_sizes, targets)# 映射回原圖detections = self.transform.postprocess(detections, images.image_sizes, original_image_sizes)  

detections = self.transform.postprocess(detections, images.image_sizes, original_image_sizes)  

補充:pytorch自帶detection模塊:

import os
import time
import torch.nn as nn
import torch
import random
import numpy as np
import torchvision.transforms as transforms
import torchvision
from PIL import Image
import torch.nn.functional as F
from tools.my_dataset import PennFudanDataset
#from tools.common_tools import set_seed
from torch.utils.data import DataLoader
from matplotlib import pyplot as plt
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.transforms import functional as F#set_seed(1)  # 設置隨機種子BASE_DIR = os.path.dirname(os.path.abspath(__file__))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")# classes_coco
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 vis_bbox(img, output, classes, max_vis=40, prob_thres=0.4):fig, ax = plt.subplots(figsize=(12, 12))ax.imshow(img, aspect='equal')out_boxes = output_dict["boxes"].cpu()out_scores = output_dict["scores"].cpu()out_labels = output_dict["labels"].cpu()num_boxes = out_boxes.shape[0]for idx in range(0, min(num_boxes, max_vis)):score = out_scores[idx].numpy()bbox = out_boxes[idx].numpy()class_name = classes[out_labels[idx]]if score < prob_thres:continueax.add_patch(plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False,edgecolor='red', linewidth=3.5))ax.text(bbox[0], bbox[1] - 2, '{:s} {:.3f}'.format(class_name, score), bbox=dict(facecolor='blue', alpha=0.5),fontsize=14, color='white')plt.show()plt.close()class Compose(object):def __init__(self, transforms):self.transforms = transformsdef __call__(self, image, target):for t in self.transforms:image, target = t(image, target)return image, targetclass RandomHorizontalFlip(object):def __init__(self, prob):self.prob = probdef __call__(self, image, target):if random.random() < self.prob:height, width = image.shape[-2:]image = image.flip(-1)bbox = target["boxes"]bbox[:, [0, 2]] = width - bbox[:, [2, 0]]target["boxes"] = bboxreturn image, targetclass ToTensor(object):def __call__(self, image, target):image = F.to_tensor(image)return image, targetif __name__ == "__main__":# configLR = 0.001num_classes = 2batch_size = 1start_epoch, max_epoch = 0, 30train_dir = os.path.join(BASE_DIR, "data", "PennFudanPed")train_transform = Compose([ToTensor(), RandomHorizontalFlip(0.5)])# step 1: datatrain_set = PennFudanDataset(data_dir=train_dir, transforms=train_transform)# 收集batch data的函數def collate_fn(batch):return tuple(zip(*batch))train_loader = DataLoader(train_set, batch_size=batch_size, collate_fn=collate_fn)# step 2: modelmodel = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)in_features = model.roi_heads.box_predictor.cls_score.in_featuresmodel.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes) # replace the pre-trained head with a new onemodel.to(device)# step 3: loss# in lib/python3.6/site-packages/torchvision/models/detection/roi_heads.py# def fastrcnn_loss(class_logits, box_regression, labels, regression_targets)# step 4: optimizer schedulerparams = [p for p in model.parameters() if p.requires_grad]optimizer = torch.optim.SGD(params, lr=LR, momentum=0.9, weight_decay=0.0005)lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)# step 5: Iterationfor epoch in range(start_epoch, max_epoch):model.train()for iter, (images, targets) in enumerate(train_loader):images = list(image.to(device) for image in images)targets = [{k: v.to(device) for k, v in t.items()} for t in targets]# if torch.cuda.is_available():#     images, targets = images.to(device), targets.to(device)loss_dict = model(images, targets)  # images is list; targets is [ dict["boxes":**, "labels":**], dict[] ]losses = sum(loss for loss in loss_dict.values())print("Training:Epoch[{:0>3}/{:0>3}] Iteration[{:0>3}/{:0>3}] Loss: {:.4f} ".format(epoch, max_epoch, iter + 1, len(train_loader), losses.item()))optimizer.zero_grad()losses.backward()optimizer.step()lr_scheduler.step()# testmodel.eval()# configvis_num = 5vis_dir = os.path.join(BASE_DIR, "data", "PennFudanPed", "PNGImages")img_names = list(filter(lambda x: x.endswith(".png"), os.listdir(vis_dir)))random.shuffle(img_names)preprocess = transforms.Compose([transforms.ToTensor(), ])for i in range(0, vis_num):path_img = os.path.join(vis_dir, img_names[i])# preprocessinput_image = Image.open(path_img).convert("RGB")img_chw = preprocess(input_image)# to deviceif torch.cuda.is_available():img_chw = img_chw.to('cuda')model.to('cuda')# forwardinput_list = [img_chw]with torch.no_grad():tic = time.time()print("input img tensor shape:{}".format(input_list[0].shape))output_list = model(input_list)output_dict = output_list[0]print("pass: {:.3f}s".format(time.time() - tic))# visualizationvis_bbox(input_image, output_dict, COCO_INSTANCE_CATEGORY_NAMES, max_vis=20, prob_thres=0.5)  # for 2 epoch for nms

歡迎點贊? ?收藏? ?關注

參考:Pytorch實現Faster-RCNN_pytorch faster rcnn-CSDN博客

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/74048.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/74048.shtml
英文地址,請注明出處:http://en.pswp.cn/web/74048.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【Matlab】-- 基于MATLAB的美賽常用多種算法

文章目錄 文章目錄 01 內容概要02 各種算法基本原理03 部分代碼04 代碼下載 01 內容概要 本資料集合了多種數學建模和優化算法的常用代碼資源&#xff0c;旨在為參與美國大學生數學建模競賽&#xff08;MCM/ICM&#xff0c;簡稱美賽&#xff09;的參賽者提供實用的編程工具和…

Vue2和Vue3響應式的基本實現

目錄 簡介Vue2 響應式Vue2 響應式的局限性 Vue3 響應式Vue3 響應式的優點 Vue2 和 Vue3 響應式對比 簡介 在 Vue 框架中&#xff0c;數據的響應式是其核心特性之一。當頁面數據發生變化時&#xff0c;我們希望界面能自動更新&#xff0c;而不是手動操作 DOM。這就需要對數據進…

Linux系統中快速安裝docker

1 查看是否安裝docker 要檢查Ubuntu是否安裝了Docker&#xff0c;可以使用以下幾種方法&#xff1a; 方法1&#xff1a;使用 docker --version 命令 docker --version如果Docker已安裝&#xff0c;輸出會顯示Docker的版本信息&#xff0c;例如&#xff1a; Docker version …

ElasticSearch 分詞器

文章目錄 一、安裝中文分詞插件Linux安裝7.14.1版本&#xff1a;測試1&#xff1a;ik_smart測試2&#xff1a;ik_max_word 二、es內置的分詞器&#xff1a;三、拼音插件安裝以及&#xff08;IKpinyin使用&#xff09;配置 IK pinyin 分詞配置 一、安裝中文分詞插件 IK Analys…

arm64位FFmpeg與X264庫

參考鏈接&#xff1a; https://blog.csdn.net/gitblog_09700/article/details/142945092

機器學習與深度學習4:數據集處理Dataset,DataLoader,batch_size

深度學習中&#xff0c;我們能看到別人的代碼中都有一個繼承Dataset類的數據集處理過程&#xff0c;這也是深度學習處理數據集的的基礎&#xff0c;下面介紹這個數據集的定義和使用&#xff1a; 1、數據集加載 1.1 通用的定義 Bach&#xff1a;表示每次喂給模型的數據 Epoc…

MySQL數據庫和表的操作之SQL語句

&#x1f3af; 本文專欄&#xff1a;MySQL深入淺出 &#x1f680; 作者主頁&#xff1a;小度愛學習 MySQL數據庫和表的操作 關系型數據庫&#xff0c;都是遵循SQL語法進行數據查詢和管理的。 SQL語句 什么是sql SQL&#xff1a;結構化查詢語言(Structured Query Language)&…

ubuntu開發mcu環境

# 編輯 vim或者vscode # 編譯 arm-none-eabi # 燒寫 openocd 若是默認安裝&#xff0c;會在/usr/share/openocd/scripts/{interface,target} 有配置接口和目標版配置 示例&#xff1a; openocd -f interface/stlink-v2.cfg -f target/stm32f1x.cfg 啟動后&#xff0c;會…

Windows模仿Mac大小寫切換, 中英文切換

CapsLock 功能優化腳本部署指南 部署步驟 第一步&#xff1a;安裝 AutoHotkey v2 訪問 AutoHotkey v2 官網下載并安裝最新版本安裝時勾選 "Add Compile Script to context menus" 第二步&#xff1a;部署腳本 直接運行 (調試推薦) 新建文本文件&#xff0c;粘貼…

Selenium Web自動化如何快速又準確的定位元素路徑,強調一遍是元素路徑

如果文章對你有用&#xff0c;請給個贊&#xff01; 匹配的ChromeDriver和瀏覽器版本是更好完成自動化的基礎&#xff0c;可以從這里去下載驅動程序&#xff1a; 最全ChromeDriver下載含win linux mac 最新版本134.0.6998.165 持續更新..._chromedriver 134-CSDN博客 如果你問…

CSRF vs SSRF詳解

一、CSRF&#xff08;跨站請求偽造&#xff09;攻擊全解 攻擊原理示意圖 受害者瀏覽器 ├── 已登錄銀行網站&#xff08;Cookie存活&#xff09; └── 訪問惡意網站執行&#xff1a;<img src"http://bank.com/transfer?tohacker&amount1000000">核心…

Python PDF解析利器:pdfplumber | AI應用開發

Python PDF解析利器&#xff1a;pdfplumber全面指南 1. 簡介與安裝 1.1 pdfplumber概述 pdfplumber是一個Python庫&#xff0c;專門用于從PDF文件中提取文本、表格和其他信息。相比其他PDF處理庫&#xff0c;pdfplumber提供了更直觀的API和更精確的文本定位能力。 主要特點…

niuhe 插件教程 - 配置 MCP讓AI更聰明

niuhe 插件官方教程已經上線, 請訪問: http://niuhe.zuxing.net niuhe 連接 MCP 介紹 API 文檔的未來&#xff1a;MCP&#xff0c;讓協作像聊天一樣簡單. MCP 是 Model Context Protocol(模型上下文協議)的縮寫&#xff0c;是 2024 年 11 月 Claude 的公司 Anthropic 推出并開…

26考研——排序_插入排序(8)

408答疑 文章目錄 二、插入排序基本概念插入排序方法直接插入排序算法描述示例性能分析 折半插入排序改進點算法步驟性能分析 希爾排序相關概念示例分析希爾排序的效率效率分析空間復雜度時間復雜度 九、參考資料鮑魚科技課件26王道考研書 二、插入排序 基本概念 定義&#x…

精華貼分享|從不同的交易理論來理解頭肩形態,殊途同歸

本文來源于量化小論壇策略分享會板塊精華帖&#xff0c;作者為孫小迪&#xff0c;發布于2025年2月17日。 以下為精華帖正文&#xff1a; 01 前言 學習了一段時間交易后&#xff0c;我發現在幾百年的歷史中&#xff0c;不同門派的交易理論對同一種市場特征的稱呼不一樣&#x…

leetcode437.路徑總和|||

對于根結點來說&#xff0c;可以選擇當前結點為路徑也可以不選擇&#xff0c;但是一旦選擇當前結點為路徑那么后續都必須要選擇結點作為路徑&#xff0c;不然路徑不連續是不合法的&#xff0c;所以這里分開出來兩個方法進行遞歸 由于力扣最后一個用例解答錯誤&#xff0c;分析…

北斗導航 | 改進奇偶矢量法的接收機自主完好性監測算法原理,公式,應用,RAIM算法研究綜述,matlab代碼

改進奇偶矢量法的接收機自主完好性監測算法研究 摘要 接收機自主完好性監測(RAIM)是保障全球導航衛星系統(GNSS)安全性的核心技術。針對傳統奇偶矢量法在噪聲敏感性、多故障隔離能力上的缺陷,本文提出一種基于加權奇偶空間與動態閾值的改進算法。通過引入觀測值權重矩陣重…

深度神經網絡全解析:原理、結構與方法對比

深度神經網絡全解析&#xff1a;原理、結構與方法對比 1. 引言 隨著人工智能的發展&#xff0c;深度神經網絡&#xff08;Deep Neural Network&#xff0c;DNN&#xff09;已經成為圖像識別、自然語言處理、語音識別、自動駕駛等領域的核心技術。相比傳統機器學習方法&#x…

經典論文解讀系列:MapReduce 論文精讀總結:簡化大規模集群上的數據處理

&#x1f9e0; MapReduce 論文解讀總結&#xff1a;簡化大規模集群上的數據處理 原文標題&#xff1a;MapReduce: Simplified Data Processing on Large Clusters 作者&#xff1a;Jeffrey Dean & Sanjay Ghemawat 發表時間&#xff1a;2004 年 發表機構&#xff1a;Google…

通過Appium理解MCP架構

MCP即Model Context Protocol&#xff08;模型上下文協議&#xff09;&#xff0c;是由Anthropic公司于2024年11月26日推出的開放標準框架&#xff0c;旨在為大型語言模型與外部數據源、工具及系統建立標準化交互協議&#xff0c;以打破AI與數據之間的連接壁壘。 MCP架構與Appi…