'Camera calibration - Distortion removal OpenCV

I am trying to get the intrinsic parameters using opencv's implementation of camera calibration. However, when I try to undistort the image with the retrieved parameters, the image becomes more distorted than before. Can anyone help me out here?

Below are the resulting images and code.

Code:


criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
chessboard_size = (6,9)
objp = np.zeros((chessboard_size[0] * chessboard_size[1], 3), np.float32)
objp[:,:2] = np.mgrid[0:chessboard_size[1], 0:chessboard_size[0]].T.reshape(-1,2)

obj_points = []
img_points = []

for image in images:
  img = cv2.imread(image)
  gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  ret, corners = cv2.findChessboardCorners(gray_img, 
                                           (chessboard_size[1], chessboard_size[0]), 
                                           None)
  if ret == True:
    obj_points.append(objp)
    corners2 = cv2.cornerSubPix(gray_img, corners, (5,5), (-1,-1), criteria)
    img_points.append(corners)
    cv2.drawChessboardCorners(img, chessboard_size, corners2, ret)

ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, gray_img.shape[::-1], None, None)

distorted_img = cv2.imread(images[5])
height, width = distorted_img.shape[:2]
corrected_camera_matrix, roi = cv2.getOptimalNewCameraMatrix(camera_matrix, 
                                                             dist, 
                                                             (width, height), 
                                                             1, 
                                                             (width, height))

undistorted_img = cv2.undistort(distorted_img, camera_matrix, dist, None, corrected_camera_matrix)

Original: Original Result: Result



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source