Python OpenCV Rectification

import cv2
import numpy as np

// Use the 3x3 M projection matrix from the intrinsic calibration
M = np.array([...]);

// Use D distortion from the intrinsic calibration (5 or 8 parameters in the standard OpenCV ordering)
D = np.array([...]);

// Use the 3x3 R rotation matrix from the extrinsic calibration
R = np.array([...]);

// Use the 3x4 P camera projection matrix from the extrinsic calibration
P = np.array([...]);

// Width of the output rectified image
width = ...;

// Height of the output rectified image
height = ...;

unrectified_image = cv2.imread('unrectified_image.png')

map_x, map_y = cv2.initUndistortRectifyMap(M, D, R, P, (wdth, height))

# Apply the transformation to the image
rectified_image = cv2.remap(unrectified_image, mapx, mapy, cv2.INTER_LINEAR)

cv2.imwrite('rectified.png', rectified_image)