1

我正在为水下航行器编写推理系统,并被告知要研究异步以改进对象跟踪。这个想法是有一个 tflite 对象检测模型,该模型检测对象并为它检测到的每个对象返回一个框/坐标,然后均值偏移(或其他一些跟踪算法然后用于跟踪对象)。但是,tflite 模型大约需要 1 秒来进行检测,这太慢了。所以我想在 meanshift 跟踪时在单独的线程中运行它,每当 tflite 模型完成时,它都会更新要跟踪的框。那样我会假设我们会有平滑的检测和跟踪。

我发现异步有点棘手,不能完全正确。出于测试目的,我创建了一个延迟 5 秒的推理函数,以清楚地模拟推理所需的时间,并创建了一个连续运行以模拟均值偏移的跟踪函数。这是我到目前为止所拥有的:

async def inference(x):
    await asyncio.sleep(x)
    return "===========Inference Done================= "

def tracking():
    print("tracking...")

def start_loop(loop):
    asyncio.set_event_loop(loop)
    loop.run_forever()


new_loop = asyncio.new_event_loop()
t = Thread(target=start_loop, args=(new_loop,))
t.start()


# start the object detection model before
box = asyncio.run_coroutine_threadsafe(inference(5), new_loop)
while True:
    if box:   # if the object detection has detected an object and return a bounding box, track it
        tracking()

    if box.done(): # if the tflite has completed its detection, start the next detection
        box = asyncio.run_coroutine_threadsafe(inference(5), new_loop)
        print(box.result())

这里的预期输出是tracking...连续===========Inference Done================= 打印,每 5 秒打印一次。然而,会发生什么是tracking...连续运行 5 秒,然后它开始这样做:

tracking...
tracking...
tracking...
tracking...
tracking...
tracking...
tracking...
tracking...
===========Inference Done================= 
tracking...
===========Inference Done================= 
tracking...

我怎样才能解决这个问题?

4

1 回答 1

2

你奇怪的输出是因为它的顺序print和分配与box它应该是相反的。你写的方式:

box = asyncio.run_coroutine_threadsafe(inference(5), new_loop)
print(box.result())

...第一次完成推理时,您安排一个新的推理并等待它完成。在下一次循环迭代中,您将打印一个“跟踪”,然后box.done()立即为真,因为您已经等待它完成。

要修复它,请颠倒顺序:

print(box.result())
box = asyncio.run_coroutine_threadsafe(inference(5), new_loop)

或改写如下:

new_box = asyncio.run_coroutine_threadsafe(inference(5), new_loop)
print(box.result())
box = new_box
于 2021-04-02T10:10:34.813 回答