与另一个线程或进程共享asyncio.Queue

时间:2019-01-25 19:53:50

标签: python-3.x opencv asynchronous python-asyncio template-matching

我最近将旧的模板匹配程序转换为asyncio,并且遇到一种情况,我的协程之一依赖于阻塞方法(processing_frame)。

每当调用该方法的协程 analyze_frame)从共享的asyncio.Queue()

我不确定这是否可行或值得,因为我对线程和多处理的经验很少

import cv2
import datetime
import argparse
import os
import asyncio

#   Making CLI
if not os.path.exists("frames"):
    os.makedirs("frames")

t0 = datetime.datetime.now()
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", required=True,
                help="path to our file")
args = vars(ap.parse_args())

threshold = .2
death_count = 0
was_found = False
template = cv2.imread('youdied.png')
vidcap = cv2.VideoCapture(args["video"])

loop = asyncio.get_event_loop()
frames_to_analyze = asyncio.Queue()


def main():
    length = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
    tasks = []
    for _ in range(int(length / 50)):
        tasks.append(loop.create_task(read_frame(50, frames_to_analyze)))
        tasks.append(loop.create_task(analyze_frame(threshold, template, frames_to_analyze)))
    final_task = asyncio.gather(*tasks)
    loop.run_until_complete(final_task)

    dt = datetime.datetime.now() - t0
    print("App exiting, total time: {:,.2f} sec.".format(dt.total_seconds()))

    print(f"Deaths registered: {death_count}")


async def read_frame(frames, frames_to_analyze):
    global vidcap
    for _ in range(frames-1):
        vidcap.grab()

    else:
        current_frame = vidcap.read()[1]
    print("Read 50 frames")
    await frames_to_analyze.put(current_frame)


async def analyze_frame(threshold, template, frames_to_analyze):
    global vidcap
    global was_found
    global death_count
    frame = await frames_to_analyze.get()
    is_found = processing_frame(frame)
    if was_found and not is_found:
        death_count += 1
        await writing_to_file(death_count, frame)
    was_found = is_found


def processing_frame(frame):
    res = cv2.matchTemplate(frame, template, cv2.TM_CCOEFF_NORMED)
    max_val = cv2.minMaxLoc(res)[1]
    is_found = max_val >= threshold
    print(is_found)
    return is_found


async def writing_to_file(death_count, frame):
    cv2.imwrite(f"frames/frame{death_count}.jpg", frame)

if __name__ == '__main__':
    main()

我尝试使用unsync,但没有成功
我会得到一些类似的东西

  

带有self._rlock:
  PermissionError:[WinError 5]访问被拒绝

1 个答案:

答案 0 :(得分:1)

如果processing_frame是一个阻止函数,则应使用await loop.run_in_executor(None, processing_frame, frame)来调用它。这样会将函数提交到线程池,并允许事件循环继续执行其他操作,直到调用函数完成。

诸如cv2.imwrite之类的呼叫也是如此。按照书面规定,writing_to_file实际上不是异步的,尽管是用async def定义的。这是因为它不等待任何内容,因此一旦开始执行,它将一直进行到最后而不会挂起。在那种情况下,首先也可以使它成为正常功能,以使正在发生的事情变得显而易见。