我正在使用PyTorch和OpenCV的YOLO算法实现一个对象检测模型.在单个视频上运行我的模型效果很好.但是,每当我试图使用多处理同时测试更多视频时,它都会冻结.你能解释一下这个代码有什么问题吗??

import torch
import cv2
import time
from multiprocessing import Process

model = torch.hub.load('ultralytics/yolov5', 'custom', path='runs/best.pt', force_reload=True)

def detectObject(video,name):
    cap = cv2.VideoCapture(video)
    while cap.isOpened():
        pTime = time.time()
        ret, img = cap.read()
        cTime = time.time()
        fps = str(int(1 / (cTime - pTime)))
        if img is None:
            break
        else:
            results = model(img)
            labels = results.xyxyn[0][:, -1].cpu().numpy()
            cord = results.xyxyn[0][:, :-1].cpu().numpy()
            n = len(labels)
            x_shape, y_shape = img.shape[1], img.shape[0]
            for i in range(n):
                row = cord[i]
                # If score is less than 0.3 we avoid making a prediction.
                if row[4] < 0.3:
                    continue
                x1 = int(row[0] * x_shape)
                y1 = int(row[1] * y_shape)
                x2 = int(row[2] * x_shape)
                y2 = int(row[3] * y_shape)
                bgr = (0, 255, 0)  # color of the box
                classes = model.names  # Get the name of label index
                label_font = cv2.FONT_HERSHEY_COMPLEX  # Font for the label.
                cv2.rectangle(img, (x1, y1), (x2, y2), bgr, 2)  # Plot the boxes
                cv2.putText(img, classes[int(labels[i])], (x1, y1), label_font, 2, bgr, 2)
                cv2.putText(img, f'FPS={fps}', (8, 70), label_font, 3, (100, 255, 0), 3, cv2.LINE_AA)

        img = cv2.resize(img, (700, 700))
        cv2.imshow(name, img)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cap.release()

Videos = ['../Dataset/Test1.mp4','../Dataset/Test2.mp4']
for i in Videos:
    process = Process(target=detectObject, args=(i, str(i)))
    process.start()

每次我运行代码时,它都会冻结.

Downloading: "https://github.com/ultralytics/yolov5/archive/master.zip" to /home/com/.cache/torch/hub/master.zip
YOLOv5 ???? 2022-6-27 Python-3.9.9 torch-1.11.0+cu102 CPU

Fusing layers... 
YOLOv5s summary: 213 layers, 7023610 parameters, 0 gradients
Adding AutoShape... 

推荐答案

我通过添加torch multiprocessing个代码来实现它.

from torch.multiprocessing import Pool, Process, set_start_method
try:
     set_start_method('spawn', force=True)
except RuntimeError:
    pass

videos = ['videos/video1.mp4', 'videos/video2.mp4']
for i in videos:
    process = Process(target=detectObject, args=(i, str(i)))
    process.start()

通过这种方式,我可以同时运行多个视频.

Python相关问答推荐

在Wayland上使用setCellWidget时,try 编辑QTable Widget中的单元格时,PyQt 6崩溃

如何从在虚拟Python环境中运行的脚本中运行需要宿主Python环境的Shell脚本?

DataFrames与NaN的条件乘法

Pandas计数符合某些条件的特定列的数量

mypy无法推断类型参数.List和Iterable的区别

如何在Python中使用Pandas将R s Tukey s HSD表转换为相关矩阵''

如何在两列上groupBy,并使用pyspark计算每个分组列的平均总价值

如何使用OpenGL使球体遵循Python中的八样路径?

如何检测鼠标/键盘的空闲时间,而不是其他输入设备?

在Python中控制列表中的数据步长

使用python playwright从 Select 子菜单中 Select 值

将字节序列解码为Unicode字符串

查找查找表中存在的列值组合

具有不同坐标的tkinter canvs.cocords()和canvs.moveto()

try 在单个WITH_COLUMNS_SEQ操作中链接表达式时,使用Polars数据帧时出现ComputeError

将.exe文件从.py转换后出现问题.";ModuleNotFoundError:没有名为';Selify;的模块

如何使用aiohttp获取图像并直接处理它而不保存它?

通过外键Django创建从一个字段到其他字段的 Select 列表

给定y的误差时,线性回归系数的计算误差

使用Python下载pdf url