基于pytorch预训练模型使用fasterrcnn调用摄像头进行目标检测无敌详细!简单!超少代码!(代码片段)

猫头丁 猫头丁     2023-02-26     256

关键词:

基于pytorch预训练模型使用Faster RCNN调用摄像头进行目标检测【无敌详细!简单!超少代码!】

详细完整项目链接:https://download.csdn.net/download/weixin_46570668/86954697?spm=1001.2014.3001.5503

使用 Pytorch 自带的预训练模型 fasterrcnn_resnet50_fpn,该模型是在COCO 数据集上进行预训练。
COCO 数据集是一个大型的、丰富的用于物体检测、分割的数据集,提供的图片类别有80 类,有超过 33 万张图片,其中 20 万张图片有标注,整个数据集中个体的数目超过 150万个。COCO2017 数据共 80 个类别,类别的 id 号不是连续的,最大为 90。

记载预训练模型代码如下:

import torch
import torchvision
model = torchvision.models.detection.fasterrcnn_resnet50_fpn(
    pretrained=True, progress=True, num_classes=91, pretrained_backbone=True)

使用OpenCV调用摄像头,代码如下:

import cv2
capture=cv2.VideoCapture(0)

获得标签及对应类别(这个文件好像可以去COCO还是Pytorch的什么网站上下载,我有点记不清了,不过我也把它和代码一起打包上传资源)

classes_path = 'classes.txt'
classes_path = os.path.expanduser(classes_path)
with open(classes_path) as f:
    class_names = f.readlines()
class_names = [c.strip() for c in class_names]
num_classes = len(class_names)

进行目标检测,并画图函数

def detect_image(image):
    start_time = time.time()
    image_shape = np.array(np.shape(image)[0:2])
    old_width = image_shape[1]
    old_height = image_shape[0]
    old_image = copy.deepcopy(image)
    width, height = get_new_img_size(old_width, old_height)
    image = image.resize([width, height])
    photo = np.array(image, dtype=np.float32) / 255
    photo = np.transpose(photo, (2, 0, 1))
    with torch.no_grad():

        model.eval()
        # Using RGB conversion to convert image pixel-wise into a numpy array
        np_sample_image = np.array(image.convert("RGB"))

        # Converting the numpy array to a tensor
        transformed_img = torchvision.transforms.transforms.ToTensor()(
            torchvision.transforms.ToPILImage()(np_sample_image))
        result = model([transformed_img])

        bbox = []
        label = []
        conf = []
        for i in range(len(result[0]['scores'])):
            if result[0]['scores'][i] > confidence:
                bbox.append(result[0]['boxes'][i].tolist())
                label.append(result[0]['labels'][i].tolist())
                conf.append(result[0]['scores'][i].tolist())
        bbox = np.array(bbox)
        label = np.array(label)
        conf = np.array(conf)
        bbox[:, 0::2] = (bbox[:, 0::2]) / width * old_width
        bbox[:, 1::2] = (bbox[:, 1::2]) / height * old_height
        bbox = np.array(bbox, np.int32)
    image = old_image
    thickness = (np.shape(old_image)[0] + np.shape(old_image)[1]) // old_width * 2
    font = ImageFont.truetype(font='simhei.ttf',
                                  size=np.floor(3e-2 * np.shape(image)[1] + 0.5).astype('int32'))

    for i, c in enumerate(label):
        predicted_class = class_names[int(c)]
        score = conf[i]

        left, top, right, bottom = bbox[i]
        top = top - 5
        left = left - 5
        bottom = bottom + 5
        right = right + 5

        top = max(0, np.floor(top + 0.5).astype('int32'))
        left = max(0, np.floor(left + 0.5).astype('int32'))
        bottom = min(np.shape(image)[0], np.floor(bottom + 0.5).astype('int32'))
        right = min(np.shape(image)[1], np.floor(right + 0.5).astype('int32'))

        # 画框框
        label = ' :.2f'.format(predicted_class, score)
        draw = ImageDraw.Draw(image)
        label_size = draw.textsize(label, font)
        label = label.encode('utf-8')
        print(label)

        if top - label_size[1] >= 0:
            text_origin = np.array([left, top - label_size[1]])
        else:
            text_origin = np.array([left, top + 1])

        for i in range(thickness):
            draw.rectangle(
                    [left + i, top + i, right - i, bottom - i],
                    outline=colors[int(c)])
        draw.rectangle(
                [tuple(text_origin), tuple(text_origin + label_size)],
                fill=colors[int(c)])
        draw.text(text_origin, str(label, 'UTF-8'), fill=(0, 0, 0), font=font)
        del draw

    print("time:", time.time() - start_time)
    return image

依次读入帧,转变格式,并送入模型进行检测

t1 = time.time()
    # 读取某一帧
    ref,frame=capture.read()
    # 格式转变,BGRtoRGB
    frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
    # 转变成Image
    frame = Image.fromarray(np.uint8(frame))
    frame = np.array(detect_image(frame))

    frame = cv2.cvtColor(frame,cv2.COLOR_RGB2BGR)
    fps  = ( fps + (1./(time.time()-t1)) ) / 2
    print("fps= %.2f"%(fps))

    cv2.imshow("video",frame)
    c= cv2.waitKey(30) & 0xff
    if c==27:
        capture.release()
        break

完整代码如下!赶紧试试看!

import numpy as np
import time
import torch
import torchvision
import os
import cv2
import copy
import colorsys
from PIL import Image, ImageFont, ImageDraw
# 调用摄像头
capture=cv2.VideoCapture(0)

fps = 0.0

model = torchvision.models.detection.fasterrcnn_resnet50_fpn(
    pretrained=True, progress=True, num_classes=91, pretrained_backbone=True)

def get_new_img_size(width, height, img_min_side=600):
    if width <= height:
        f = float(img_min_side) / width
        resized_height = int(f * height)
        resized_width = int(img_min_side)
    else:
        f = float(img_min_side) / height
        resized_width = int(f * width)
        resized_height = int(img_min_side)

    return resized_width, resized_height

# classes_path = 'voc_classes.txt'
classes_path = 'classes.txt'
classes_path = os.path.expanduser(classes_path)
with open(classes_path) as f:
    class_names = f.readlines()
class_names = [c.strip() for c in class_names]
num_classes = len(class_names)
mean = torch.Tensor([0,0,0,0]).cuda().repeat(num_classes+1)[None]
std = torch.Tensor([0.1, 0.1, 0.2, 0.2]).cuda().repeat(num_classes+1)[None]
# 画框设置不同的颜色
hsv_tuples = [(x / len(class_names), 1., 1.)
              for x in range(len(class_names))]
colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
colors = list(
    map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),
                colors))
#---------------------------------------------------#
#   获得所有的分类
#---------------------------------------------------#

confidence = 0.5
def detect_image(image):
    start_time = time.time()
    image_shape = np.array(np.shape(image)[0:2])
    old_width = image_shape[1]
    old_height = image_shape[0]
    old_image = copy.deepcopy(image)
    width, height = get_new_img_size(old_width, old_height)
    image = image.resize([width, height])
    photo = np.array(image, dtype=np.float32) / 255
    photo = np.transpose(photo, (2, 0, 1))
    with torch.no_grad():

        model.eval()
        # Using RGB conversion to convert image pixel-wise into a numpy array
        np_sample_image = np.array(image.convert("RGB"))

        # Converting the numpy array to a tensor
        transformed_img = torchvision.transforms.transforms.ToTensor()(
            torchvision.transforms.ToPILImage()(np_sample_image))
        result = model([transformed_img])

        bbox = []
        label = []
        conf = []
        for i in range(len(result[0]['scores'])):
            if result[0]['scores'][i] > confidence:
                bbox.append(result[0]['boxes'][i].tolist())
                label.append(result[0]['labels'][i].tolist())
                conf.append(result[0]['scores'][i].tolist())
        bbox = np.array(bbox)
        label = np.array(label)
        conf = np.array(conf)
        bbox[:, 0::2] = (bbox[:, 0::2]) / width * old_width
        bbox[:, 1::2] = (bbox[:, 1::2]) / height * old_height
        bbox = np.array(bbox, np.int32)
    image = old_image
    thickness = (np.shape(old_image)[0] + np.shape(old_image)[1]) // old_width * 2
    font = ImageFont.truetype(font='simhei.ttf',
                                  size=np.floor(3e-2 * np.shape(image)[1] + 0.5).astype('int32'))

    for i, c in enumerate(label):
        predicted_class = class_names[int(c)]
        score = conf[i]

        left, top, right, bottom = bbox[i]
        top = top - 5
        left = left - 5
        bottom = bottom + 5
        right = right + 5

        top = max(0, np.floor(top + 0.5).astype('int32'))
        left = max(0, np.floor(left + 0.5).astype('int32'))
        bottom = min(np.shape(image)[0], np.floor(bottom + 0.5).astype('int32'))
        right = min(np.shape(image)[1], np.floor(right + 0.5).astype('int32'))

        # 画框框
        label = ' :.2f'.format(predicted_class, score)
        draw = ImageDraw.Draw(image)
        label_size = draw.textsize(label, font)
        label = label.encode('utf-8')
        print(label)

        if top - label_size[1] >= 0:
            text_origin = np.array([left, top - label_size[1]])
        else:
            text_origin = np.array([left, top + 1<

基于pytorch预训练模型使用fasterrcnn调用摄像头进行目标检测无敌详细!简单!超少代码!(代码片段)

基于pytorch预训练模型使用FasterRCNN调用摄像头进行目标检测【无敌详细!简单!超少代码!】详细完整项目链接:https://download.csdn.net/download/weixin_46570668/86954697?spm=1001.2014.3001.5503使用Pytorch自带的预训练模型fasterr... 查看详情

如何加载部分预训练的 pytorch 模型?

】如何加载部分预训练的pytorch模型?【英文标题】:HowcanIloadapartialpretrainedpytorchmodel?【发布时间】:2020-07-2710:00:01【问题描述】:我正在尝试让pytorch模型在句子分类任务上运行。当我处理医学笔记时,我正在使用ClinicalBert(https:... 查看详情

使用预训练的 pytorch vgg16 模型及其类进行分类

】使用预训练的pytorchvgg16模型及其类进行分类【英文标题】:Classificationwithpretrainedpytorchvgg16modelanditsclasses【发布时间】:2020-10-1010:05:21【问题描述】:我用pytorch的预训练vgg16模型写了一个图像vgg分类模型。importmatplotlib.pyplotasplti... 查看详情

基于预训练模型的unet超级简单懒人版pytorch版(代码片段)

基于预训练模型的Unet【超级简单】【懒人版】【Pytorch版】在本项目开始前,首先给大家保证,本次项目只是一个最简单的Unet实现,使用现成的代码,不需要手写代码,使用预训练模型,不需要标注数据集... 查看详情

pytorch预训练(代码片段)

前言最近使用PyTorch感觉妙不可言,有种当初使用Keras的快感,而且速度还不慢。各种设计直接简洁,方便研究,比tensorflow的臃肿好多了。今天让我们来谈谈PyTorch的预训练,主要是自己写代码的经验以及论坛PyT... 查看详情

Pytorch 预训练模型中的类数

】Pytorch预训练模型中的类数【英文标题】:TheNumberofClassesinPytorchPretrainedModel【发布时间】:2021-10-2900:08:20【问题描述】:我想使用Pytorch中的预训练模型在自己的数据集中进行图像分类,但是我应该如何在冻结特征提取层的参数... 查看详情

pytorch如何给预训练模型添加新的层

参考技术A在使用pytorch预训练模型的时候发现预训练模型的输出层没有激活函数,为了提高模型的训练效果需要自己添加。以ResNet50为例:输出的模型为:可以看到最后的输出层是没有激活函数的,因此我们需要队fc层进行修改:... 查看详情

pytorch预训练(代码片段)

前言最近使用PyTorch感觉妙不可言,有种当初使用Keras的快感,而且速度还不慢。各种设计直接简洁,方便研究,比tensorflow的臃肿好多了。今天让我们来谈谈PyTorch的预训练,主要是自己写代码的经验以及论坛PyT... 查看详情

Pytorch - 跳过计算每个时期的预训练模型的特征

】Pytorch-跳过计算每个时期的预训练模型的特征【英文标题】:Pytorch-skipcalculatingfeaturesofpretrainedmodelsforeveryepoch【发布时间】:2022-01-1103:29:21【问题描述】:我习惯于使用tenserflow-keras,但现在我不得不开始使用Pytorch来解决灵活性... 查看详情

Pytorch 中的预训练模型

】Pytorch中的预训练模型【英文标题】:Pre-trainedmodelinPytorch【发布时间】:2019-09-1122:43:57【问题描述】:我刚刚加载了预训练模型3Dresnethttps://github.com/kenshohara/3D-ResNets-PyTorch.从文件“resnext-101-kinetics.pth”上方的链接下载后,我以... 查看详情

微调预训练模型 MobileNet_V3_Large PyTorch

】微调预训练模型MobileNet_V3_LargePyTorch【英文标题】:FineTuningPretrainedModelMobileNet_V3_LargePyTorch【发布时间】:2021-11-1803:23:53【问题描述】:我正在尝试添加一个层来微调MobileNet_V3_Large预训练模型。我查看了PyTorch文档,但他们没有... 查看详情

如何使用 PyTorch 在预训练模型上添加新层? (给出了 Keras 示例。)

】如何使用PyTorch在预训练模型上添加新层?(给出了Keras示例。)【英文标题】:HowcanIaddnewlayersonpre-trainedmodelwithPyTorch?(Kerasexamplegiven.)【发布时间】:2021-02-1406:09:06【问题描述】:我正在与Keras合作,并尝试分析由具有有意义权... 查看详情

最强nlp预训练模型库pytorch-transformers正式开源:支持6个预训练框架,27个预训练模型

先上开源地址:https://github.com/huggingface/pytorch-transformers#quick-tour官网:https://huggingface.co/pytorch-transformers/index.htmlPyTorch-Transformers(正式名称为pytorch-pretrained-bert)是一个用于自然语言处理(NLP)的最先进的预训练 查看详情

六pytorch进阶训练技巧(代码片段)

六、PyTorch进阶训练技巧文章目录六、PyTorch进阶训练技巧1.自定义损失函数1.1.函数定义1.2.类定义1.2.1.DiceLoss1.2.2.DiceBCELoss1.2.3.IoULoss1.2.4.FocalLoss2.动态调整学习率2.1.使用官方提供的scheduler2.2.自定义scheduler3.模型微调-torchvision3.1使用... 查看详情

我如何知道 Pytorch 中预训练模型的架构?

】我如何知道Pytorch中预训练模型的架构?【英文标题】:Howcaniknowthearchitectureofpre-trainedmodelinPytorch?【发布时间】:2020-12-0811:30:45【问题描述】:我已经下载了这个用于人脸识别的预训练模型“model_ir_se50.pth”。它给出了非常好的... 查看详情

4.使用预训练的pytorch网络进行图像分类(代码片段)

4.使用预训练的PyTorch网络进行图像分类这篇博客将介绍如何使用PyTorch预先训练的网络执行图像分类。利用这些网络只需几行代码就可以准确地对1000个常见对象类别进行分类。这些图像分类网络是开创性的、最先进的图像分类网... 查看详情

4.使用预训练的pytorch网络进行图像分类(代码片段)

4.使用预训练的PyTorch网络进行图像分类这篇博客将介绍如何使用PyTorch预先训练的网络执行图像分类。利用这些网络只需几行代码就可以准确地对1000个常见对象类别进行分类。这些图像分类网络是开创性的、最先进的图像分类网... 查看详情

pytorch——gpt-2预训练模型及文本生成(代码片段)

介绍在本次将学习另一个有着优秀表现的预训练模型:GPT-2模型,以及使用它进行文本生成任务实践。知识点GPT-2的核心思想GPT-2模型结构详解GPT-2进行文本生成OpenAI在论文ImprovingLanguageUnderstandingbyGenerativePre-Training中提出了GPT模型... 查看详情