camera calibration for distorted images with chess board samples reads distorted images, calculates the calibration and write undistorted images
original code is from opencv tutorials:
https://github.com/opencv/opencv/blob/master/samples/python/calibrate.py
https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_calib3d/py_pose/py_pose.html
read more about the functions here:
https://docs.opencv2.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html
a reference calibration plane for printing can be copied from here:
In [1]:
# to run in google colab
import sys
if 'google.colab' in sys.modules:
import subprocess
subprocess.call('apt-get install subversion'.split())
subprocess.call('svn export https://github.com/YoniChechik/AI_is_Math/trunk/c_07_camera_calibration/images'.split())
In [2]:
import numpy as np
import cv2
from glob import glob
import matplotlib.pyplot as plt
In [3]:
square_size=2.88
img_mask='./images/*.jpeg'
pattern_size = (9, 6)
figsize = (20,20)
In [4]:
img_names = glob(img_mask)
num_images = len(img_names)
pattern_points = np.zeros((np.prod(pattern_size), 3), np.float32)
pattern_points[:, :2] = np.indices(pattern_size).T.reshape(-1, 2)
pattern_points *= square_size
obj_points = []
img_points = []
h, w = cv2.imread(img_names[0]).shape[:2]
In [5]:
plt.figure(figsize=figsize)
for i,fn in enumerate(img_names):
print('processing %s... ' % fn)
imgBGR = cv2.imread(fn)
if imgBGR is None:
print("Failed to load", fn)
continue
imgRGB = cv2.cvtColor(imgBGR,cv2.COLOR_BGR2RGB)
img = cv2.cvtColor(imgRGB,cv2.COLOR_RGB2GRAY)
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 you want to better improve the accuracy... cv2.findChessboardCorners already uses cv2.cornerSubPix
# if found:
# term = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1)
# cv2.cornerSubPix(img, corners, (5, 5), (-1, -1), term)
if not found:
print('chessboard not found')
continue
if i<12:
img_w_corners = cv2.drawChessboardCorners(imgRGB, pattern_size, corners, found)
plt.subplot(4,3,i+1)
plt.imshow(img_w_corners)
print(' %s... OK' % fn)
img_points.append(corners.reshape(-1, 2))
obj_points.append(pattern_points)
plt.show()