Skip to content

Instantly share code, notes, and snippets.

@kor01
Last active August 20, 2017 08:37
Show Gist options
  • Save kor01/d8bcff95b864168c7d6eb477c08dbab6 to your computer and use it in GitHub Desktop.
Save kor01/d8bcff95b864168c7d6eb477c08dbab6 to your computer and use it in GitHub Desktop.
[cv2 cheatsheet] #cv2
# number of inner corners in x and y direction
nx = 8
ny = 6
#find chessboard corners
img = mpimg.imread(images[idx])
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Find the chessboard corners
ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)
# If found, draw corners
if ret == True:
# Draw and display the corners
cv2.drawChessboardCorners(img, (nx, ny), corners, ret)
plt.imshow(img)
# 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('./Cal*.jpg')
# Step through the list and search for chessboard corners
for idx, fname in enumerate(images):
img = mpimg.imread(fname)
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Find the chessboard corners
ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)
# If found, add object points, image points
if ret == True:
objpoints.append(objp)
imgpoints.append(corners)
# compute the calibration coefficient
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_size, None, None)
# undistort the image
img = # read from somewhere
undist = cv2.undistort(img, mtx, dist, None, mtx)
#visualize and compare
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(img)
ax1.set_title('Original Image', fontsize=50)
ax2.imshow(undist)
ax2.set_title('Undistorted Image', fontsize=50)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
hsv_img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment