栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python多线程+opencv 视频读取错误解决方法

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python多线程+opencv 视频读取错误解决方法

python多线程+opencv 视频读取错误解决方法

错误代码:

import opencv as cv
import threading

cap = cv.VideoCapture('1.mp4')
# 线程执行函数
def detect():
    try:
        ret, frame = cap.read()
    except:
        return None
    
if __name__ == '__main__':
    threads = []
    for i in range(3):
        t = threading.Thread(detect)
        threads.append(t)
    for t in threads:
        t.setDaemon(True)
        t.start()
    for t in threads:
        t.join()

执行结果:
程序崩溃

可能原因分析:
多个线程同时读取视频文件时,存在线程同步问题,导致程序崩溃

解决方法:
使用锁机制,当某个线程读取视频文件时加锁,读取完当前帧后解锁。

import opencv as cv
import threading
cap = cv.VideoCapture('1.mp4')
lock = threading.Lock  # 生成线程锁

# 自定义多线程类
class MyThread(threading.Thread):
    def __init__(self, func, args=()):
    	super(MyThread, self).__init__()
        self.func = func
        self.args = args
    def run():
        lock.aquire()  # 加锁
        self.func()
        lock.release()  # 解锁

# 线程执行函数
def detect():
    try:
        ret, frame = cap.read()
    except:
        return None
    
if __name__ == '__main__':
    threads = []
    for i in range(3):
        t = threading.Thread(detect)
        threads.append(t)
    for t in threads:
        t.setDaemon(True)
        t.start()
    for t in threads:
        t.join()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/308004.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号