如何在视频流的每一帧上运行并行线程来应用函数?

2024-09-24 00:30:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用一个烧瓶申请

  • 从网络摄像头捕获视频流
  • 在每一帧上应用对象检测算法
  • 同时以视频的形式显示具有边界框的帧和由上述函数提供的数据

问题是由于函数运算,结果呈现有点滞后。为了克服这个问题,我尝试在另一个线程上运行这个函数。 你能帮我在视频的每一帧上运行这个函数并以视频的形式显示结果帧吗? 我的主要功能类似于:

def detect_barcode():
global vs, outputFrame, lock


total = 0

# loop over frames from the video stream
while True:
    frame = vs.read()
    frame = imutils.resize(frame, width=400)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (7, 7), 0)
    timestamp = datetime.datetime.now()
    cv2.putText(frame, timestamp.strftime(
        "%A %d %B %Y %I:%M:%S%p"), (10, frame.shape[0] - 10),
        cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
    if total > frameCount:
        # detect barcodes in the image
        barcodes = md.detect(gray)

        # check to see if barcode was found
        if barcode in barcodes:
            x,y,w,h = cv2.boundRect(barcode)
        cv2.rectangle(frame,x,y,(x+w),(y+h),(255,0,0),2)
    total += 1
    # lock
    with lock:
        outputFrame = frame.copy()
if __name__ == '__main__':

# start a thread that will perform motion detection
t = threading.Thread(target=detect_barcode)
t.daemon = True
t.start()
app.run(debug=True)

vs.stop()

Tags: 函数truelock视频ifcv2framebarcode
1条回答
网友
1楼 · 发布于 2024-09-24 00:30:41

我真的做了这样的事。我的解决方案是asyncio的concurrent.futures模块

import concurrent.futures as futures

基本上,您可以创建执行器并“提交”阻塞方法作为参数。它返回一个名为Future的东西,您可以检查每一帧的结果(如果有的话)

executor = futures.ThreadPoolExecutor()

将初始化执行器

future_obj = executor.submit(YOUR_FUNC, *args)

将开始执行。稍后你可以查看它的状态

if future_obj.done():
    print(future_obj.result())
else:
    print("task running")
    # come back next frame and check again

相关问题 更多 >