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

标签 python multithreading opencv computer-vision

我正在尝试使用 flask 制作一个应用程序

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

问题在于,由于函数操作,结果渲染有一点滞后。为了克服这个问题,我尝试在另一个线程上运行该函数。 您能否帮助在视频的每一帧上运行该函数并以视频的形式显示结果帧? 我的主要功能看起来有点像:

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

最佳答案

我确实只是做了这样的事情。我的解决方案是 asyncio 的 concurrent.futures模块。

将并发.futures 导入为 future

基本上,您创建执行器并“提交”您的阻塞方法作为参数。它返回一个名为 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

关于python - 如何运行并行线程以在视频流的每一帧上应用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59113838/

相关文章:

java - 如何关闭无限循环锁定的套接字?

c++ - 使用 OpenCV 的低质量空中拼接

python - 如何在 pandas 数据帧上使用 pool.starmap()?

javascript - 从 JavaScript 中查找 id 的正则表达式

python - 如何控制QSplitter内部的间距

multithreading - 这是 glibc/pthread 中的错误吗?

asp.net - Signalr - 将用户名与 ConnectionId 关联

Python Django easy-maps 不呈现谷歌地图

opencv - 缺少文件错误 ndk-build

opencv - 使用JavaCV拼接图像 : compilation error