【问题标题】:Get output from function with while loop to use elsewhere (python)使用while循环从函数获取输出以在其他地方使用(python)
【发布时间】:2021-07-27 20:03:04
【问题描述】:

我有一个功能,可以从视频图像中检测一个点并在帧上画一个点。现在我需要其他地方的点的 x,y 位置,但由于 while 循环,我无法从函数中获取我需要的信息。由于下面的代码是现在,该函数只返回视频停止后的最后一个已知值。我也尝试将 return 语句放在 while 循环中,但循环由于 return 语句而中断。我说的是 xy_side 我在函数之外的某个地方需要它并且我需要它实时(所以不要将所有值存储在列表中并在之后显示列表)。 有人能帮我吗? 代码是用python写的。

def det_point(folder,fn,model):
    cap = cv2.VideoCapture("./" + folder + "/" + fn)
    red = (0, 0, 255)
    while(cap.isOpened()):
        ret, frame = cap.read()
        crds = detect_point_prop(frame,model)
        cntr_crds = float_to_int(crds[0])
        start_crds = float_to_int(crds[1])
        end_crds = float_to_int(crds[2])
        frame = cv2.circle(frame, cntr_crds, 3, red, 5)
        frame = cv2.rectangle(frame, start_crds, end_crds, green, 5)
        cv2.imshow("Image", frame)
        xy_side = cntr_crds
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    return  xy_side

【问题讨论】:

  • 这是什么语言?
  • Python,很抱歉没有提及

标签: python function while-loop return break


【解决方案1】:

我建议您使用线程安全队列。在您的情况下,您可以将队列传递给det_point,这会将值推送到队列中。然后,您可以在另一个线程中运行消费者以使用 det_point 放入队列中的值。

python 队列库有一个很好的例子来说明如何启动一个调用消费者的线程。

https://docs.python.org/3/library/queue.html#queue.Queue.join

import threading, queue

q = queue.Queue()

def worker():
    while True:
        item = q.get()
        print(f'Working on {item}')
        print(f'Finished {item}')
        q.task_done()

# turn-on the worker thread
threading.Thread(target=worker, daemon=True).start()

# send thirty task requests to the worker for item in range(30):
q.put(item) print('All task requests sent\n', end='')

# block until all tasks are done q.join() print('All work completed')

在您的情况下,需要来自 det_point 的输出值的函数将替换工作函数。此外,我会将队列作为参数传递给工作线程,而不是使用全局变量。

【讨论】:

    猜你喜欢
    • 2011-10-20
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    相关资源
    最近更新 更多