From 2feb0c2f613c63792f17eb14b4f846c37748c1e5 Mon Sep 17 00:00:00 2001
From: Arthur Pastel <arthur.pastel@telecom-paristech.fr>
Date: Thu, 23 Nov 2017 19:27:11 +0100
Subject: [PATCH] Merge pull request #9895 from art049:parrallel_calibration_py

* Adding threading in calibrate.py

* samples: update calibrate.py
---
 samples/python/calibrate.py | 55 ++++++++++++++++++++++++-------------
 1 file changed, 36 insertions(+), 19 deletions(-)

diff --git a/samples/python/calibrate.py b/samples/python/calibrate.py
index 00dfe57fe6..a5c4a91f5e 100755
--- a/samples/python/calibrate.py
+++ b/samples/python/calibrate.py
@@ -30,18 +30,19 @@ if __name__ == '__main__':
     import getopt
     from glob import glob
 
-    args, img_mask = getopt.getopt(sys.argv[1:], '', ['debug=', 'square_size='])
+    args, img_mask = getopt.getopt(sys.argv[1:], '', ['debug=', 'square_size=', 'threads='])
     args = dict(args)
     args.setdefault('--debug', './output/')
     args.setdefault('--square_size', 1.0)
+    args.setdefault('--threads', 4)
     if not img_mask:
-        img_mask = '../data/left*.jpg'  # default
+        img_mask = '../data/left??.jpg'  # default
     else:
         img_mask = img_mask[0]
 
     img_names = glob(img_mask)
     debug_dir = args.get('--debug')
-    if not os.path.isdir(debug_dir):
+    if debug_dir and not os.path.isdir(debug_dir):
         os.mkdir(debug_dir)
     square_size = float(args.get('--square_size'))
 
@@ -52,16 +53,16 @@ if __name__ == '__main__':
 
     obj_points = []
     img_points = []
-    h, w = 0, 0
-    img_names_undistort = []
-    for fn in img_names:
-        print('processing %s... ' % fn, end='')
+    h, w = cv2.imread(img_names[0], 0).shape[:2]  # TODO: use imquery call to retrieve results
+
+    def processImage(fn):
+        print('processing %s... ' % fn)
         img = cv2.imread(fn, 0)
         if img is None:
             print("Failed to load", fn)
-            continue
+            return None
 
-        h, w = img.shape[:2]
+        assert w == img.shape[1] and h == img.shape[0], ("size: %d x %d ... " % (img.shape[1], img.shape[0]))
         found, corners = cv2.findChessboardCorners(img, pattern_size)
         if found:
             term = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1)
@@ -71,19 +72,29 @@ if __name__ == '__main__':
             vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
             cv2.drawChessboardCorners(vis, pattern_size, corners, found)
             path, name, ext = splitfn(fn)
-            outfile = debug_dir + name + '_chess.png'
+            outfile = os.path.join(debug_dir, name + '_chess.png')
             cv2.imwrite(outfile, vis)
-            if found:
-                img_names_undistort.append(outfile)
 
         if not found:
             print('chessboard not found')
-            continue
+            return None
 
-        img_points.append(corners.reshape(-1, 2))
-        obj_points.append(pattern_points)
+        print('           %s... OK' % fn)
+        return (corners.reshape(-1, 2), pattern_points)
 
-        print('ok')
+    threads_num = int(args.get('--threads'))
+    if threads_num <= 1:
+        chessboards = [processImage(fn) for fn in img_names]
+    else:
+        print("Run with %d threads..." % threads_num)
+        from multiprocessing.dummy import Pool as ThreadPool
+        pool = ThreadPool(threads_num)
+        chessboards = pool.map(processImage, img_names)
+
+    chessboards = [x for x in chessboards if x is not None]
+    for (corners, pattern_points) in chessboards:
+        img_points.append(corners)
+        obj_points.append(pattern_points)
 
     # calculate camera distortion
     rms, camera_matrix, dist_coefs, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, (w, h), None, None)
@@ -94,10 +105,16 @@ if __name__ == '__main__':
 
     # undistort the image with the calibration
     print('')
-    for img_found in img_names_undistort:
+    for fn in img_names if debug_dir else []:
+        path, name, ext = splitfn(fn)
+        img_found = os.path.join(debug_dir, name + '_chess.png')
+        outfile = os.path.join(debug_dir, name + '_undistorted.png')
+
         img = cv2.imread(img_found)
+        if img is None:
+            continue
 
-        h,  w = img.shape[:2]
+        h, w = img.shape[:2]
         newcameramtx, roi = cv2.getOptimalNewCameraMatrix(camera_matrix, dist_coefs, (w, h), 1, (w, h))
 
         dst = cv2.undistort(img, camera_matrix, dist_coefs, None, newcameramtx)
@@ -105,7 +122,7 @@ if __name__ == '__main__':
         # crop and save the image
         x, y, w, h = roi
         dst = dst[y:y+h, x:x+w]
-        outfile = img_found + '_undistorted.png'
+
         print('Undistorted image written to: %s' % outfile)
         cv2.imwrite(outfile, dst)