关于pytorch的yolov3的video文件

关于pytorch的yolov3的video文件


代码来自 eriklindernoren /yolov3,由于作者没有给出video代码,故在这里给出。
参考中3的代码感觉有多余部分(比如rgb和bgr的转换),去掉了一些多余的。增加了fps计算

参考:

  1. GitHub的pytorch版YOLOv3 链接:https://github.com/eriklindernoren/PyTorch-YOLOv3
  2. YOLOv3 论文作者的github链接:https://github.com/pjreddie/darknet
  3. Guardian-Li给出的video代码:https://github.com/eriklindernoren/PyTorch-YOLOv3/issues/485

附上代码

from __future__ import division

from models import *
from utils.utils import *
from utils.datasets import *

import time
import argparse
import cv2
import torch
from torch.autograd import Variable


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--image_folder", type=str, default="data/samples", help="path to dataset")
    parser.add_argument("--video_file", type=str, default=r"C:\Users\DELL\Desktop\project\opencv_combat\walking_people.mp4", help="path to dataset")
    parser.add_argument("--model_def", type=str, default="config/yolov3.cfg", help="path to model definition file")
    parser.add_argument("--weights_path", type=str, default="weights/yolov3.weights", help="path to weights file")
    parser.add_argument("--class_path", type=str, default="data/coco.names", help="path to class label file")
    parser.add_argument("--conf_thres", type=float, default=0.6, help="object confidence threshold")
    parser.add_argument("--nms_thres", type=float, default=0.4, help="iou thresshold for non-maximum suppression")
    parser.add_argument("--batch_size", type=int, default=1, help="size of the batches")
    parser.add_argument("--n_cpu", type=int, default=3, help="number of cpu threads to use during batch generation")
    parser.add_argument("--img_size", type=int, default=416, help="size of each image dimension")
    parser.add_argument("--checkpoint_model", type=str, help="path to checkpoint model")
    opt = parser.parse_args()
    print(opt)


    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model = Darknet(opt.model_def, img_size=opt.img_size).to(device)
    if opt.weights_path.endswith(".weights"):
        # Load darknet weights
        model.load_darknet_weights(opt.weights_path)
    else:
        # Load checkpoint weights
        model.load_state_dict(torch.load(opt.weights_path))
    model.eval()  # Set in evaluation mode
    classes = load_classes(opt.class_path)
    Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor


    #if opt.vedio_file.endswith(".mp4"):
    cap = cv2.VideoCapture(opt.video_file)
    colors = np.random.randint(0, 255, size=(len(classes), 3), dtype="uint8")

    start = time.time()
    frames = 0
    #NUM=0
    while cap.isOpened():
        ret, img = cap.read()
        if ret is False:
            break
        # img = cv2.resize(img, (1280, 960), interpolation=cv2.INTER_CUBIC)
        # RGBimg=changeBGR2RGB(img)
        imgTensor = transforms.ToTensor()(img)
        imgTensor, _ = pad_to_square(imgTensor, 0)
        imgTensor = resize(imgTensor, opt.img_size)
        #加一个维度
        imgTensor = imgTensor.unsqueeze(0)
        imgTensor = Variable(imgTensor.type(Tensor))
        with torch.no_grad():
            detections = model(imgTensor)
            detections = non_max_suppression(detections, opt.conf_thres, opt.nms_thres)

        if detections[0] is  None:
            pass
        else:
            # output is a list and have one element,we can achieve the array
            output = detections[0]
            detections = rescale_boxes(output, opt.img_size, img.shape[:2])
            unique_labels = detections[:, -1].cpu().unique()
            n_cls_preds = len(unique_labels)
            for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections:
                box_w = x2 - x1
                box_h = y2 - y1
                color = [int(c) for c in colors[int(cls_pred)]]
                #print(cls_conf)
                img = cv2.rectangle(img, (x1, y1 + box_h), (x2, y1), color, 2)
                cv2.putText(img, classes[int(cls_pred)], (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
                cv2.putText(img, str("%.2f" % float(conf)), (x2, y2 - box_h), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                            color, 2)
        #计算fps
        frames += 1
        print("FPS of the video is {:5.4f}".format(frames / (time.time() - start)))
        cv2.imshow('frame',img)
        #cv2.waitKey(0)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()
### 回答1: Ubuntu 18.04是一种操作系统,而PyTorch是一个开源的深度学习框架,而YoloV5是一个基于PyTorch实现的目标检测算法。 在Ubuntu 18.04上安装PyTorchYoloV5可以通过以下步骤完成: 1. 安装Python:Ubuntu自带Python,可以通过终端命令检查当前安装的Python版本。确保工作环境中已经安装了Python3。 2. 安装PyTorch:可以通过官方网站提供的命令进行安装,比如使用pip命令:`pip3 install torch torchvision`。 3. 克隆YoloV5仓库:在终端中执行以下命令克隆YoloV5的GitHub仓库:`git clone https://github.com/ultralytics/yolov5.git`。 4. 安装依赖项:进入克隆下来的YoloV5文件夹,运行`pip3 install -r requirements.txt`命令安装YoloV5所需的依赖项。 5. 下载预训练模型:YoloV5需要一个预训练的权重文件。可以通过运行`python3 models/export.py --weights yolov5s.pt`命令来下载预训练模型。 6. 运行目标检测:在YoloV5的文件夹中,可以使用命令`python3 detect.py --source your_image.jpg`来对一张图像进行目标检测。将`your_image.jpg`替换为实际的图像文件路径即可。 通过以上步骤,你就可以在Ubuntu 18.04上使用PyTorchYoloV5进行目标检测了。当然,还可以进一步学习和探索YoloV5的其他功能和用法,以满足更多的需求。 ### 回答2: Ubuntu 18.04是一种操作系统,而pytorchyolov5是两个在Ubuntu 18.04上可以使用的工具。 Ubuntu 18.04是一个基于Linux的开源操作系统,它提供了稳定性和安全性,并且拥有广泛的软件支持。它适合用于各种计算机任务,包括机器学习和深度学习。 PyTorch是一个非常流行的用于构建深度学习模型的Python库。它提供了丰富的工具和函数,使得开发人员可以更轻松地创建、训练和评估模型。PyTorch在Ubuntu 18.04上可以通过包管理器进行安装,也可以通过源代码进行安装。 YOLOv5是一个基于深度学习的实时目标检测算法。它使用了PyTorch作为后端,可以用于检测图像和视频中的多个对象,并输出它们的位置和类别。YOLOv5可以在Ubuntu 18.04上使用PyTorch进行安装和运行。 要在Ubuntu 18.04上使用PyTorchYOLOv5,首先需要安装Python环境和PyTorch库。可以使用pip命令安装PyTorch,具体的安装步骤可以在PyTorch官方网站上找到。 安装完成后,需要下载YOLOv5的源代码并进行配置。可以从YOLOv5的GitHub页面上获取源代码,并按照说明进行设置。然后,可以使用PyTorch加载已经训练好的YOLOv5模型,并用它来对图像或视频进行目标检测。 总结来说,在Ubuntu 18.04上使用PyTorchYOLOv5进行目标检测,需要先安装PyTorch和配置YOLOv5的源代码。然后,可以使用PyTorch加载模型进行目标检测。这样就可以在Ubuntu 18.04上使用PyTorchYOLOv5进行目标检测了。 ### 回答3: Ubuntu 18.04是一个主流的Linux操作系统,而PyTorch是一个开源的深度学习框架,Yolov5是一种目标检测算法的版本。现在我来回答关于Ubuntu 18.04上安装PyTorch Yolov5的问题。 首先,要在Ubuntu 18.04上安装PyTorch,你可以通过使用pip包管理器来完成。你可以打开终端,并运行以下命令来安装最新版本的PyTorch: ``` pip install torch torchvision ``` 接下来,下载Yolov5的源代码。你可以在GitHub上找到官方仓库(https://github.com/ultralytics/yolov5),并将其克隆到你的机器上: ``` git clone https://github.com/ultralytics/yolov5.git ``` 然后,进入yolov5文件夹,并安装所需的依赖项: ``` cd yolov5 pip install -r requirements.txt ``` 安装完成后,你可以使用已经训练好的权重文件来测试Yolov5的性能,或者你也可以使用自己的数据训练一个新的模型。如果你有自己的数据集,你需要将它们准备好,并编辑相应的配置文件。 最后,你可以使用以下命令运行Yolov5检测: ``` python detect.py --source path/to/image/or/video ``` 这将会运行Yolov5算法,并对指定路径的图像或视频进行目标检测。 总结起来,安装PyTorch Yolov5需要在Ubuntu 18.04上安装PyTorchYOLOv5源代码,并进行相应的配置和数据准备工作,然后就可以使用Python命令来运行目标检测了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值