python - 如何使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)
解决方案
您可以将 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
推荐阅读
- flutter - 移动到其他页面时无法保持底部导航栏颤动
- javascript - 像 (if:) 这样的更改需要在它们之间使用 + 组合
- c# - 锁定一个对象和所有子对象
- android - 如何在 Flutter 中使用 Google Play Install Referrer
- javascript - 如何从 CDN 将 javascript 添加到 webflow 站点
- google-api - FetchError:对 https://www.googleapis.com/oauth2/v4/token 的请求失败
- node.js - 部署后在我的 Express 应用程序上获取 404
- javascript - 获取对象的键是否存在于嵌套对象和数组中
- assembly - 在磁盘上读取或写入之前无法获得正确的状态
- alert - 对于未出现在 grafana 中以进行警报的情况