700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python无限循环语句的代码_如何在Python中实现非阻塞无限循环

python无限循环语句的代码_如何在Python中实现非阻塞无限循环

时间:2021-07-06 00:04:36

相关推荐

python无限循环语句的代码_如何在Python中实现非阻塞无限循环

我有一个无限循环,从网络摄像头读取视频帧,每个帧将通过一个复杂的功能,需要高计算能力.因此,当显示帧时,由于阻塞代码,程序会感觉有点迟钝.

我现在打算做的是,

>仅在目标对象出现时收集前几帧

>将它们放入单独的线程中以避免代码阻塞.

我每秒测量网络摄像头捕获的帧数,即~28帧.因此,while循环每秒只收集前5个帧并在另一个线程中处理所有这些帧,并在完成所有5个函数后返回结果.

我试图使用’Pool’和’Queue’但是无法使它工作,循环仍然被阻止.下面的代码模糊地表示我的程序现在的样子,我回家后会编辑它,现在使用手机发布.

def detect(frame):

# detect target object from images

pass

def nn(frame):

# some heavy processing code

pass

count = 0

stack = []

while True:

frame = cv2.imread(0)

detected = detect(frame)

# stop collecting images when collected 5

if detected and count <= 5:

stack.append(frame)

count += 1

# start processing

if len(stack) == 5:

p = Pool(4)

results = p.map(nn, frame)

p.close()

p.join()

# reset

stack = []

count = 0

我的概念是否正确?或者我需要做一些像协程一样的事情?

最佳答案 我用

rq解决了这个问题.

python的简单消息队列.

首先,需要异步运行的方法的实现.

它将运行你的nn函数,在这种情况下,

然后,为消息队列设置一个简单的配置,

我使用redis包中的connectionPool.

基本上,您将整个任务发送到由rq worker执行的并行进程.

def nn(frame):

# some heavy processing code

pass

def asynch_call(frame):

p = Pool(4)

results = p.map(nn, frame)

p.close()

p.join()

pool = redis.ConnectionPool(

host=HOST,

port=PORT,

password=PASS,

db=0)

r = redis.Redis(connection_pool=pool)

q = Queue('nn_queue', connection=r)

count = 0

stack = []

while True:

frame = cv2.imread(0)

detected = detect(frame)

# stop collecting images when collected 5

if detected and count <= 5:

stack.append(frame)

count += 1

# start processing

if len(stack) == 5:

job = q.enqueue(asynch_call, frame, timeout=any_long_timeout )

if job.status=='queued':

print("Job submission ok")

# reset

stack = []

count = 0

为了启动一个将处理异步调用的worker,你有几个选项,为Worker创建自己的代码,或者只是在一个单独的终端中运行以下命令:

rq worker nn_queue

请参阅上面使用的队列名称命令以发送作业.

我希望它有所帮助.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。