Raspberry pi camera module calibration using OpenCV

Before you begin reading this blog, if you have not checked my previous blog about adding a speed sensor to the sensor stack and integrate it with raspberry pi, then check it out.

Camera Model
Distortion coefficients
Images captured by Rapberry Pi
# Number of object points
num_intersections_in_x = 7
num_intersections_in_y = 7

# Size of square in meters
square_size = 0.0225

# Arrays to store 3D points and 2D image points
obj_points = []
img_points = []

# Prepare expected object 3D object points (0,0,0), (1,0,0) ...
object_points = np.zeros((7*7,3), np.float32)
object_points[:,:2] = np.mgrid[0:7, 0:7].T.reshape(-1,2)
object_points = object_points*square_size

fnames = glob.glob('path/to/images/'+'*.'+'jpg')
# Find chess board corners
ret, corners = cv2.findChessboardCorners(gray_scale, (num_intersections_in_x, num_intersections_in_y), None)
if ret:

# Draw the corners
drawn_img = cv2.drawChessboardCorners(img, (7,7), corners, ret)
cv2.imshow("main", drawn_img)
Detected corners drawn on a chess board.
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, img_size, None, None)
dist_pickle = {}
dist_pickle["mtx"] = mtx
dist_pickle["dist"] = dist
pickle.dump(dist_pickle, open("dist_pickle.p", "wb"))
undst_image = cv2.undistort(img, mtx, dist, None, mtx)
Comparison of image before and after distortion.
Photo by Adam Winger on Unsplash

Autonomous Vehicles Algorithm Developer