使用multiprocessing并行YOLOv8视频检测仅单函数执行问题求助
问题分析与解决方案
你的代码核心问题是进程创建时的target参数传递错误,导致两个检测函数并非真正并行执行:
错误点拆解
- 创建
mp.Process时,你写的是target=Detection.first_detector(),这会直接在主进程中执行first_detector()函数,等它执行完才会创建进程,而非把函数作为任务交给子进程。同理second_detector()也是一样,所以实际是主进程先跑完第一个检测,再跑第二个,根本没用到多进程并行。 - 类中的方法没有定义为静态方法,直接调用会存在语法隐患
- 最后
join()重复调用了P2.join(),漏掉了对P1的等待
修正后的代码
from ultralytics import YOLO import os import cv2 import multiprocessing as mp source1 = os.path.join('.','football-video.mp4') source2 = os.path.join('.','people.mp4') def first_detector(): model1 = YOLO('yolov8n.pt') for i in range(20): print(" first_detector is executing ********") model1.predict(source=source1, save=False, device='cpu') def second_detector(): model2 = YOLO('yolov8n.pt') for i in range(20): print(" second_detector is executing ********") model2.predict(source=source2, save=False, device='cpu') if __name__=="__main__": # target传函数对象,不要加括号调用 P1 = mp.Process(target=first_detector) P2 = mp.Process(target=second_detector) P1.start() P2.start() # 等待两个进程都结束 P1.join() P2.join()
关键修改说明
- target参数传递正确:把
target=Detection.first_detector()改成target=first_detector(去掉括号),这样才是将函数本身作为子进程的执行任务,而非先执行函数再传结果。 - 简化函数定义:把类中的方法改成普通函数,避免类方法的静态/实例方法问题,更适合多进程场景。如果一定要用类,可以给方法加上
@staticmethod装饰器,比如:
class Detection: @staticmethod def first_detector(): # 原内容不变
- 修正join逻辑:分别调用
P1.join()和P2.join(),确保主进程等待两个子进程都执行完毕再退出。
这样修改后,两个视频的检测任务会在独立的子进程中并行运行,你就能同时获取两个视频的检测结果了。
内容的提问来源于stack exchange,提问作者Hmd
相关产品推荐
相关产品推荐

