【问题标题】:How to time out a statement in a for loop如何使for循环中的语句超时
【发布时间】:2019-05-14 03:12:45
【问题描述】:

我正在编写一个 python 脚本来使用 OpenCV 执行相机校准。

我发现cv2.findChessboardCorners 函数可能需要很长时间才能在某些图像上运行。

因此,我希望能够在经过一段时间后停止该功能,然后转到下一张图像。

我该怎么做?

for fname in images:        
    img = cv2.imread(fname)                            
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, corners = cv2.findChessboardCorners(gray, (20, 17), None)   

【问题讨论】:

标签: python opencv


【解决方案1】:

您可以将 Pebble 用作多处理库,它允许调度任务。下面的代码也使用了多线程进行处理:

from pebble import ProcessPool
from concurrent.futures import TimeoutError
import cv2
import glob
import os

CALIB_FOLDER = "path/to/folder"
# chessboard size
W = 10
H = 7


def f(fname):
    img = cv2.imread(fname)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Find the chessboard corners
    ret, corners = cv2.findChessboardCorners(gray, (W-1, H-1), None)
    return ret, corners


calib_imgs = glob.glob(os.path.join(CALIB_FOLDER, "*.jpg"))
calib_imgs = sorted(calib_imgs)

futures = []
with ProcessPool(max_workers=6) as pool:
    for fname in calib_imgs:          
        future = pool.schedule(f, args=[fname], timeout=10)
        futures.append(future)

for idx, future in enumerate(futures):
    try:
        ret, corners = future.result()  # blocks until results are ready
        print(ret)
    except TimeoutError as error:
        print("{} skipped. Took longer than {} seconds".format(calib_imgs[idx], error.args[1]))
    except Exception as error:
        print("Function raised %s" % error)
        print(error.traceback)  # traceback of the function

【讨论】:

    猜你喜欢
    • 2017-11-17
    • 1970-01-01
    • 2021-10-01
    • 2011-08-17
    • 2014-08-28
    • 2016-06-16
    • 2019-06-09
    相关资源
    最近更新 更多