首页 > 解决方案 > 如何使for循环中的语句超时

问题描述

我正在编写一个 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)   

标签: pythonopencv

解决方案


您可以将 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

推荐阅读