轻松学Pytorch –使用torchvision实现对象检测

时间:2022-07-22
本文章向大家介绍轻松学Pytorch –使用torchvision实现对象检测,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

大家好,前面一篇文章介绍了torchvision的模型ResNet50实现图像分类,这里再给大家介绍一下如何使用torchvision自带的对象检测模型Faster-RCNN实现对象检测。Torchvision自带的对象检测模型是基于COCO数据集训练的,最小分辨率支持800, 最大支持1333的输入图像。

Faster-RCNN模型

Faster-RCNN模型的基础网络是ResNet50, ROI生成使用了RPN,加上头部组成。图示如下:

在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()

运行结果下:

视频实时对象检测

基于OpenCV实现视频文件或者摄像头读取,完成视频的实时对象检测,代码实现如下:

 1capture = cv.VideoCapture("D:/images/video/vehicle.ts")
 2while True:
 3    ret, frame = capture.read()
 4    if ret is not True:
 5        break
 6    blob = transform(frame)
 7    c, h, w = blob.shape
 8    input_x = blob.view(1, c, h, w)
 9    output = model(input_x.cuda())[0]
10    boxes = output['boxes'].cpu().detach().numpy()
11    scores = output['scores'].cpu().detach().numpy()
12    labels = output['labels'].cpu().detach().numpy()
13    index = 0
14    for x1, y1, x2, y2 in boxes:
15        if scores[index] > 0.5:
16            cv.rectangle(frame, (np.int32(x1), np.int32(y1)),
17                         (np.int32(x2), np.int32(y2)), (0, 255, 255), 1, 8, 0)
18            label_id = labels[index]
19            label_txt = coco_names[str(label_id)]
20            cv.putText(frame, label_txt, (np.int32(x1), np.int32(y1)), cv.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 255), 1)
21        index += 1
22    wk = cv.waitKey(1)
23    if wk == 27:
24        break
25    cv.imshow("video detection Demo", frame)

运行结果如下: