[英]How to time out a statement in a for loop
我正在編寫一個 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.