处理自己的视频数据并训练

获取视频数据的信息

import cv2


if __name__ == "__main__":
    video_path = "视频路径"
    cap = cv2.VideoCapture(video_path)
    # 视频总的帧数
    frame_num = cap.get(7)
    # 图片帧率
    fps = cap.get(5)

    while True:
         ret, frame = cap.read()
         print(f"视频帧率{fps} 视频总帧数{frame_num } 视频分辨率{frame.shape}")

通过上述代码就能获取到视频帧率、帧数、分辨率信息,根据需求自行确立采样的分辨率与帧数。

将视频数据转换为npy数据

npy数据的好处:读取速度快,省去了解码时间
坏处:增加了空间
这是一种时间换空间的策略

import cv2
import numpy as np


if __name__ == "__main__":
    video_path = "视频路径"
    cap = cv2.VideoCapture(video_path)
    # 获取帧率
    fps = int(cap.get(5))
    frame_lists = []
    while True:
        ret, frame = cap.read()
        if not(ret):
            break
        # 对图片数据做缩小,缩小为224*224
        frame = cv2.resize(frame, (224, 224))
        # 将三维数据转换为一维
        frame_array = frame.reshape(-1)
        frame_lists.append(frame_array)
    # 根据视频帧率和目标帧率计算采样周期
    interval = int(fps / 20)
    frame_lists = np.array(frame_lists)[::interval]
    # 保存数据
    np.save("npy文件保存地址", frame_lists)

数据加载模块

这是pytorch的数据加载器,这块掌握了基本就ok了,哪都用得上。

from torch.utils.data import Dataset, DataLoader

class MyDataset(Dataset):
    def __init__(self, txt, load_type="test"):
        self.load_type = load_type
        with open(txt, "r") as file:
            self.data = file.readlines()

    def __getitem__(self, idx):
        video_path = self.data[idx].strip()
        data = np.load(video_path)
        # 数据的保存样式[20, 224*223*3 + label]
        # 加载20张图片数据
        imgs = data[:, :-1].reshape(20, 224, 224, 3)
        label = data[:, -1:].reshape(-1)
        return imgs, label[0]

    def __len__(self):
        return len(self.data)

训练模型

代码大致如下,需要掌握一些api,并且理解数据的流动。

from torch.utils.data import Dataset, DataLoader
# 加载模型
from models.model import COMP_F
import torch
import numpy as np
from tqdm import tqdm
from time import sleep
import os
torch.backends.cudnn.benchmark = True


def save_matrix(file, epoch, train_matrix, test_matrix, mode="a+"):
	"""
	保存混淆矩阵
	"""
    with open(file, mode) as f:
        f.writelines(f"epoch: {epoch}\n")
        f.writelines(f"train_matrix: {train_matrix}\n")
        f.writelines(f"test_matrix: {test_matrix}\n")


def save_acc(file, epoch, acc, loss, lr, mode="a+"):
	"""
	保存训练准确度、学习率等信息
	"""
    with open(file, mode) as f:
        f.writelines(f"{epoch}\n")
        f.writelines(f"{acc}\n")
        f.writelines(f"{loss}\n")
        f.writelines(f"{lr}\n")


def calculate_matrix(predicted, label, matrix):
	"""
	计算混淆矩阵
	"""
    for pre_y, real_y in zip(predicted, label):
        if not(f"{pre_y}_{real_y}" in matrix.keys()):
            matrix[f"{pre_y}_{real_y}"] = 0
        matrix[f"{pre_y}_{real_y}"] += 1


class MyDataset(Dataset):
    def __init__(self, txt, load_type="test"):
        self.load_type = load_type
        with open(txt, "r") as file:
            self.data = file.readlines()

    def __getitem__(self, idx):
        video_path = self.data[idx].strip()
        data = np.load(video_path)
        # 数据的保存样式[20, 224*223*3 + label]
        # 加载20张图片数据
        imgs = data[:, :-1].reshape(20, 224, 224, 3)
        label = data[:, -1:].reshape(-1)
        return imgs, label[0]

    def __len__(self):
        return len(self.data)


if __name__ == "__main__":
	# 将需要训练的数据的路径写入txt
    train_path = "../txt/train.txt"
    test_path = "../txt/test.txt"
    # 加载数据
    dataset = MyDataset(train_path, load_type="train")
    train_dataloader = DataLoader(dataset, batch_size=8, shuffle=True, num_workers=4, pin_memory=True)
    dataset = MyDataset(test_path, load_type="test")
    test_dataloader = DataLoader(dataset, batch_size=4, shuffle=False, pin_memory=True)

    Epochs = 500
    criterion = torch.nn.CrossEntropyLoss()
    device = "cuda"
	# 模型的大小
    model_type = "resnet18"
    os.makedirs(f"{model_type}", exist_ok=True)
    os.makedirs(f"{model_type}/log", exist_ok=True)

    model = COMP_F(model_type).to(device)
    optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
    scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=10, eta_min=1e-8)
    last_acc = 0

    save_matrix(file=f"{model_type}/log/matrix.txt", epoch=" ", train_matrix=" ", test_matrix=" ", mode="w")
    save_acc(file=f"{model_type}/log/acc.txt", epoch=" ", acc=" ", loss=" ", lr=" ", mode="w")

    for epoch in range(Epochs):
        model.train()
        train_loss = 0
        batch_num = 0
        train_correct = 0
        sample_num = 0
        train_matrix = {}
        with open(f"{model_type}/log/异常数据.txt", "a+") as error_file:
            for sample, label in tqdm(train_dataloader):
                sample, label = torch.permute(sample.to(device) / 255, (0, 4, 1, 2, 3)), label.to(device)
                # print(sample.shape, label.shape)
                optimizer.zero_grad()
                output = model(sample)
                loss = criterion(output, label)
                loss.backward()
                optimizer.step()

                batch_num += 1
                train_loss += loss.item()
                _, predicted = torch.max(output, 1)
                sample_num += label.size(0)
                train_correct += (predicted == label).sum()
                # 计算混淆矩阵
                calculate_matrix(predicted.cpu().numpy(), label.cpu().numpy(), train_matrix)

            train_acc = train_correct.item() / sample_num
            train_loss = train_loss / batch_num

            # 测试
            model.eval()
            test_loss = 0
            batch_num = 0
            test_correct = 0
            sample_num = 0
            test_matrix = {}
            with torch.no_grad():
                try:
                    for sample, label in tqdm(test_dataloader):
                        sample, label = torch.permute(sample.to(device) / 255, (0, 4, 1, 2, 3)), label.to(device)
                        optimizer.zero_grad()
                        output = model(sample)
                        loss = criterion(output, label)

                        batch_num += 1
                        test_loss += loss.item()
                        _, predicted = torch.max(output, 1)
                        calculate_matrix(predicted.cpu().numpy(), label.cpu().numpy(), test_matrix)
                        sample_num += label.size(0)
                        test_correct += (predicted == label).sum()

                except:
                    pass

            test_acc = test_correct.item() / sample_num
            torch.save(model.state_dict(), f'./{model_type}/train_{epoch}_{test_acc:.4f}.pth')
            test_loss = test_loss / batch_num

            save_matrix(file=f"{model_type}/log/matrix.txt", epoch=epoch, train_matrix=train_matrix, test_matrix=test_matrix)
            save_acc(file=f"{model_type}/log/acc.txt", epoch=epoch, acc=f"train_acc: {train_acc:.4f}  test_acc: {test_acc:.4f}"
                     , loss=f"training_loss:{train_loss:.5f} test_loss:{test_loss:.5f}", lr=f"Lr:{scheduler.get_last_lr()}")
            print(f"Epoch: {epoch} training_loss:{train_loss:.5f} test_loss:{test_loss:.5f}")
            print(f"train_acc: {train_acc:.4f}  test_acc: {test_acc:.4f}")

        scheduler.step()
        adjusted_lr = scheduler.get_last_lr()
        print(f"Epoch Lr:{adjusted_lr}\n")
        sleep(1)

结尾

如果觉得文章对你有用请点赞、关注
群内交流更多技术
130856474

  • 14
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
YOLO系列是基于深度学习的端到端实时目标检测方法。 PyTorch版的YOLOv5轻量而性能高,更加灵活和易用,当前非常流行。 本课程将手把手地教大家使用labelImg标注和使用YOLOv5训练自己的数据集。课程实战分为两个项目:单目标检测(足球目标检测)和多目标检测(足球和梅西同时检测)。 本课程的YOLOv5使用ultralytics/yolov5,在Windows系统上做项目演示。包括:安装YOLOv5、标注自己的数据集、准备自己的数据集、修改配置文件、使用wandb训练可视化工具、训练自己的数据集、测试训练出的网络模型和性能统计。 希望学习Ubuntu上演示的同学,请前往 《YOLOv5(PyTorch)实战:训练自己的数据集(Ubuntu)》课程链接:https://edu.csdn.net/course/detail/30793  本人推出了有关YOLOv5目标检测的系列课程。请持续关注该系列的其它视频课程,包括:《YOLOv5(PyTorch)目标检测实战:训练自己的数据集》Ubuntu系统 https://edu.csdn.net/course/detail/30793Windows系统 https://edu.csdn.net/course/detail/30923《YOLOv5(PyTorch)目标检测:原理与源码解析》课程链接:https://edu.csdn.net/course/detail/31428《YOLOv5目标检测实战:Flask Web部署》课程链接:https://edu.csdn.net/course/detail/31087《YOLOv5(PyTorch)目标检测实战:TensorRT加速部署》课程链接:https://edu.csdn.net/course/detail/32303《YOLOv5目标检测实战:Jetson Nano部署》课程链接:https://edu.csdn.net/course/detail/32451《YOLOv5+DeepSORT多目标跟踪与计数精讲》课程链接:https://edu.csdn.net/course/detail/32669《YOLOv5实战口罩佩戴检测》课程链接:https://edu.csdn.net/course/detail/32744《YOLOv5实战中国交通标志识别》课程链接:https://edu.csdn.net/course/detail/35209《YOLOv5实战垃圾分类目标检测》课程链接:https://edu.csdn.net/course/detail/35284       
UrtheCast视频数据集是由Canada's UrtheCast公司开发和维护的一个全球视频图像数据库。该数据集包含了来自全球各地的高分辨率视频图像,这些图像是通过UrtheCast卫星系统捕获的。这个卫星系统由两颗卫星组成,它们分别是Resurs-P和Deimos-2。 UrtheCast公司的目标是为全球用户提供实时的地球影像数据,并将这些数据用于各种应用领域,包括农业、城市规划、环境监测和气象预测等。他们的视频数据集可以提供高精度的图像,以帮助用户更好地了解地球表面的变化和趋势。 UrtheCast视频数据集的特点包括以下几点: 1. 全球覆盖:该数据集收集了全球范围内的高分辨率视频图像,用户可以获取来自不同地区的图像数据。 2. 实时更新:数据集提供实时的图像更新,用户可以获取最新的地球表面图像信息。 3. 高分辨率:经过处理和增强的图像具有较高的分辨率,用户可以看到更多地表细节。 4. 多角度观测:由于卫星系统的两个卫星的不同角度拍摄,用户可以获取到同一地点多个角度的图像,进一步提高了数据的使用价值。 5. 多种应用:该数据集可用于多种应用领域,包括环境保护、资源管理、天气预报以及灾害监测等。 总之,UrtheCast视频数据集是一个提供全球高分辨率实时视频图像的数据库,可以帮助用户更好地了解和监测地球表面的变化情况,为不同领域的应用提供支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值