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()

你可能感兴趣的:(opencv,python)