Skip to content

Instantly share code, notes, and snippets.

@codebudo
Created February 24, 2019 01:39
Show Gist options
  • Save codebudo/9362f8ebe2e1e858e84f3b2e934f7828 to your computer and use it in GitHub Desktop.
Save codebudo/9362f8ebe2e1e858e84f3b2e934f7828 to your computer and use it in GitHub Desktop.
import numpy as np
import cv2 as cv
import glob
import pickle
# termination criteria
criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((6*6,3), np.float32)
objp[:,:2] = np.mgrid[0:6,0:6].T.reshape(-1,2)
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.
images = glob.glob('images/*.jpg')
for fname in images:
print(fname)
img = cv.imread(fname)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# Find the chess board corners
ret, corners = cv.findChessboardCorners(gray, (6,6), None)
# If found, add object points, image points (after refining them)
if ret == True:
objpoints.append(objp)
corners2 = cv.cornerSubPix(gray,corners, (11,11), (-1,-1), criteria)
imgpoints.append(corners)
# Draw and display the corners
cv.drawChessboardCorners(img, (6,6), corners2, ret)
#cv.imshow('img', img)
cv.imwrite(fname+'_lines.jpg', img)
#cv.waitKey(500)
ret, mtx, dist, rvecs, tvecs = cv.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
print(ret, mtx, dist, rvecs, tvecs)
fileHandle = open("calibration.pickle",'wb')
pickle.dump([ret, mtx, dist, rvecs, tvecs], fileHandle)
fileHandle.close()
for fname in images:
img = cv.imread(fname)
h, w = img.shape[:2]
newcameramtx, roi = cv.getOptimalNewCameraMatrix(mtx, dist, (w,h), 1, (w,h))
# undistort
dst = cv.undistort(img, mtx, dist, None, newcameramtx)
# undistort method 2
#mapx, mapy = cv.initUndistortRectifyMap(mtx, dist, None, newcameramtx, (w,h), 5)
#dst = cv.remap(img, mapx, mapy, cv.INTER_LINEAR)
# crop the image
x, y, w, h = roi
dst = dst[y:y+h, x:x+w]
#cv.imshow('img', dst)
#cv.waitKey(500)
cv.imwrite(fname+'_undistorted.jpg', dst)
cv.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment