# STEP 1: Compute the camera calibration matrix and distortion coefficients given a set of chessboard images.

# Run the code in the cell below to extract object points and image points for camera calibration.
import numpy as np
import cv2
import glob
# import matplotlib
# matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import pickle

CHESSBOARD_X = 9    # !number of corners of calibration chessboard in x direction
CHESSBOARD_Y = 6    # !number of corners of calibration chessboard in y direction

# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((CHESSBOARD_Y*CHESSBOARD_X,3), np.float32)
objp[:,:2] = np.mgrid[0:CHESSBOARD_X, 0:CHESSBOARD_Y].T.reshape(-1,2)

# Arrays to store object points and image points from all the images.
objpoints = [] # 3d points in real world space
imgpoints = [] # 2d points in image plane.

# Make a list of calibration images
images = glob.glob('camera_cal/calibration*.jpg')

# Step through the list and search for chessboard corners
for idx, fname in enumerate(images):
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Find the chessboard corners
    ret, corners = cv2.findChessboardCorners(gray, (CHESSBOARD_X,CHESSBOARD_Y), None)

    # If found, add object points, image points
    if ret == True:
        objpoints.append(objp)
        imgpoints.append(corners)

        # Draw and display the corners
        cv2.drawChessboardCorners(img, (CHESSBOARD_X,CHESSBOARD_Y), corners, ret)
        #write_name = 'corners_found'+str(idx)+'.jpg'
        #cv2.imwrite(write_name, img)
        cv2.imshow('img', img)
        cv2.waitKey(10)

cv2.destroyAllWindows()




# Use objpoints and imgpoints to do camera calibration.
# Run the cell below to calibrate, calculate distortion coefficients, and test undistortion on an image!

# Test undistortion on an image
img = cv2.imread('camera_cal/test_image.jpg')
img_size = (img.shape[1], img.shape[0])

# Do camera calibration given object points and image points
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_size,None,None)


dst = cv2.undistort(img, mtx, dist, None, mtx)
cv2.imwrite('camera_cal/test_undist.jpg',dst)

# Save the camera calibration result for later use (we won't worry about rvecs / tvecs)
dist_pickle = {}
dist_pickle["mtx"] = mtx
dist_pickle["dist"] = dist
pickle.dump( dist_pickle, open( "camera_cal/cali_pickle.p", "wb" ) )
#dst = cv2.cvtColor(dst, cv2.COLOR_BGR2RGB)
print("Unable to visualize undistortion due to plotting error.")
print("Pickle file successfully saved.")

'''
# Visualize undistortion
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10))
ax1.imshow(img)
ax1.set_title('Original Image', fontsize=30)
ax2.imshow(dst)
ax2.set_title('Undistorted Image', fontsize=30)
'''

# STEP 1: Compute the camera calibration matrix and distortion coefficients given a set of chessboard images.

# Run the code in the cell below to extract object points and image points for camera calibration.
import numpy as np
import cv2
import glob
# import matplotlib
# matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import pickle

CHESSBOARD_X = 9    # !number of corners of calibration chessboard in x direction
CHESSBOARD_Y = 6    # !number of corners of calibration chessboard in y direction

# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((CHESSBOARD_Y*CHESSBOARD_X,3), np.float32)
objp[:,:2] = np.mgrid[0:CHESSBOARD_X, 0:CHESSBOARD_Y].T.reshape(-1,2)

# Arrays to store object points and image points from all the images.
objpoints = [] # 3d points in real world space
imgpoints = [] # 2d points in image plane.

# Make a list of calibration images
images = glob.glob('camera_cal/calibration*.jpg')

# Step through the list and search for chessboard corners
for idx, fname in enumerate(images):
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Find the chessboard corners
    ret, corners = cv2.findChessboardCorners(gray, (CHESSBOARD_X,CHESSBOARD_Y), None)

    # If found, add object points, image points
    if ret == True:
        objpoints.append(objp)
        imgpoints.append(corners)

        # Draw and display the corners
        cv2.drawChessboardCorners(img, (CHESSBOARD_X,CHESSBOARD_Y), corners, ret)
        #write_name = 'corners_found'+str(idx)+'.jpg'
        #cv2.imwrite(write_name, img)
        cv2.imshow('img', img)
        cv2.waitKey(10)

cv2.destroyAllWindows()




# Use objpoints and imgpoints to do camera calibration.
# Run the cell below to calibrate, calculate distortion coefficients, and test undistortion on an image!

# Test undistortion on an image
img = cv2.imread('camera_cal/test_image.jpg')
img_size = (img.shape[1], img.shape[0])

# Do camera calibration given object points and image points
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_size,None,None)


dst = cv2.undistort(img, mtx, dist, None, mtx)
cv2.imwrite('camera_cal/test_undist.jpg',dst)

# Save the camera calibration result for later use (we won't worry about rvecs / tvecs)
dist_pickle = {}
dist_pickle["mtx"] = mtx
dist_pickle["dist"] = dist
pickle.dump( dist_pickle, open( "camera_cal/cali_pickle.p", "wb" ) )
#dst = cv2.cvtColor(dst, cv2.COLOR_BGR2RGB)
print("Unable to visualize undistortion due to plotting error.")
print("Pickle file successfully saved.")

'''
# Visualize undistortion
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10))
ax1.imshow(img)
ax1.set_title('Original Image', fontsize=30)
ax2.imshow(dst)
ax2.set_title('Undistorted Image', fontsize=30)
'''

# STEP 1: Compute the camera calibration matrix and distortion coefficients given a set of chessboard images. # Run the code in the cell below to extract object points and image points for camera calibration. # import matplotlib # matplotlib.use('TkAgg') # !number of corners of calibration chessboard in x direction # !number of corners of calibration chessboard in y direction # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) # Arrays to store object points and image points from all the images. # 3d points in real world space # 2d points in image plane. # Make a list of calibration images # Step through the list and search for chessboard corners # Find the chessboard corners # If found, add object points, image points # Draw and display the corners #write_name = 'corners_found'+str(idx)+'.jpg' #cv2.imwrite(write_name, img) # Use objpoints and imgpoints to do camera calibration. # Run the cell below to calibrate, calculate distortion coefficients, and test undistortion on an image! # Test undistortion on an image # Do camera calibration given object points and image points # Save the camera calibration result for later use (we won't worry about rvecs / tvecs) #dst = cv2.cvtColor(dst, cv2.COLOR_BGR2RGB) # Visualize undistortion f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10)) ax1.imshow(img) ax1.set_title('Original Image', fontsize=30) ax2.imshow(dst) ax2.set_title('Undistorted Image', fontsize=30)