1. 作者介紹
楊金鵬,男,西安工程大學電子信息學院,2022級研究生
研究方向:機器視覺與人工智能
電子郵件:1394026082@qq.com
路治東,男,西安工程大學電子信息學院,2022級研究生,張宏偉人工智能課題組
研究方向:機器視覺與人工智能
電子郵件:2063079527@qq.com
2. Faster RCNN基本框架
Faster RCNN檢測部分主要可以分為四個模塊:
(1)conv layers。即特征提取網(wǎng)絡,用于提取特征。通過一組conv+relu+pooling層來提取圖像的feature maps,用于后續(xù)的RPN層和取proposal。
(2)RPN(Region Proposal Network)。即區(qū)域候選網(wǎng)絡,該網(wǎng)絡替代了之前RCNN版本的Selective Search,用于生成候選框。這里任務有兩部分,一個是分類:判斷所有預設anchor是屬于positive還是negative(即anchor內(nèi)是否有目標,二分類);還有一個bounding box regression:修正anchors得到較為準確的proposals。因此,RPN網(wǎng)絡相當于提前做了一部分檢測,即判斷是否有目標(具體什么類別這里不判),以及修正anchor使框的更準一些。
(3)RoI Pooling。即興趣域池化(SPP net中的空間金字塔池化),用于收集RPN生成的proposals(每個框的坐標),并從(1)中的feature maps中提取出來(從對應位置扣出來),生成proposals feature maps送入后續(xù)全連接層繼續(xù)做分類(具體是哪一類別)和回歸。
(4)Classification and Regression。利用proposals feature maps計算出具體類別,同時再做一次bounding box regression獲得檢測框最終的精確位置。
3.模型訓練及測試
3.1 數(shù)據(jù)集
訓練前需要制作數(shù)據(jù)集,進行數(shù)據(jù)準備。采用收線送線裝置實時采集圖片,圖像大小為1536*1280,然后進行標注,最后送進網(wǎng)絡進行訓練。為模擬檢測的現(xiàn)場效果,劃分了紗線中常見的四種常見缺陷:毛圈、毛團、分叉以及毛瑕,并通過標注軟件對數(shù)據(jù)集進行了標注。標注文件放在VOC2007/ Annotations,圖像文件放在VOC2007/JPEGImages目錄下,生成ImageSet\Main里的四個txt文件,分別是:trainval.txt(訓練和驗證集總和)、train.txt(訓練集)、val.txt(驗證集)、test.txt(測試集),訓練集/驗證集/測試集比例為6:2:2。
3.2 環(huán)境配置
3.3 訓練參數(shù)
(1)修改lib/datasets/pascal_voc.py,將類別改成自己的類別。這里有一個注意點就是,這里的類別以及之前的類別名稱最好是全部小寫,假如是大寫的話,則會報keyError的錯誤
(2)根據(jù)實際需求及硬件情況設置代碼中的相關(guān)參數(shù),需要修改–num-classes、–data-path和–weights-path 等參數(shù),訓練過程如圖所示。
如圖所示為預測結(jié)果
3.4 訓練參數(shù)
PicoDet測試
如圖所示為訓練過程及預測結(jié)果
YOLOv3測試
如圖所示為訓練過程及預測結(jié)果
3.5 代碼展示
import os
import time
import torch
import torchvision.transforms as transforms
import torchvision
from PIL import Image
from matplotlib import pyplot as plt
# 獲取當前路徑
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'
]
if __name__ == "__main__":
# 檢測圖片路徑
path_img = os.path.join(BASE_DIR, "xxxx.jpg")
# 預處理
preprocess = transforms.Compose([
transforms.ToTensor(),
])
input_image = Image.open(path_img).convert("RGB")
img_chw = preprocess(input_image)
# 加載預訓練模型
model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
model.eval()
# if torch.cuda.is_available():
# img_chw = img_chw.to('cuda')
# model.to('cuda')
# 前向傳播
input_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))
# 打印輸出信息
for k, v in output_dict.items():
print("key:{}, value:{}".format(k, v))
# 取得相應結(jié)果
out_boxes = output_dict["boxes"].cpu()
out_scores = output_dict["scores"].cpu()
out_labels = output_dict["labels"].cpu()
# 可視化
fig, ax = plt.subplots(figsize=(12, 12))
ax.imshow(input_image, aspect='equal')
num_boxes = out_boxes.shape[0]
max_vis = 400
thres = 0.6
# 循環(huán)描框
for idx in range(0, min(num_boxes, max_vis)):
score = out_scores[idx].numpy()
bbox = out_boxes[idx].numpy()
class_name = COCO_INSTANCE_CATEGORY_NAMES[out_labels[idx]]
if score < thres:
continue
ax.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')
ax.set_title("test_result", fontsize=28, color='blue')
plt.show()
plt.savefig("test_result.png")
plt.close()
3.6 問題及分析
訓練參數(shù)調(diào)試及環(huán)境配置
在訓練前要注意將所需的環(huán)境配置好,同時所調(diào)用的庫版本是否符合要求,各個庫之間有時也需要版本一一對應。在訓練時參數(shù)的調(diào)試非常重要,對模型的檢測效果有著非常重要的影響,要多去嘗試多做實驗探究不同參數(shù)對模型的影響。
準備數(shù)據(jù)集
在數(shù)據(jù)集采集過程中要注意盡可能避免外界干擾,同時注意打光方式以及亮度等等,確保能夠把待檢測的物體和缺陷采集清晰。雖然數(shù)據(jù)集在整個項目中看起來不太重要,但是數(shù)據(jù)集采集的是否清晰,標注的是否正確等都會對檢測結(jié)果造成很大的影響。文章來源:http://www.zghlxwxcb.cn/news/detail-466733.html
參考(可供參考的鏈接和引用文獻)
1.鏈接: [http://t.csdn.cn/JrWZ1]
2.鏈接: [http://t.csdn.cn/TjQov]文章來源地址http://www.zghlxwxcb.cn/news/detail-466733.html
到了這里,關(guān)于基于Faster R-CNN實現(xiàn)目標檢測的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!