参考:https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_calib3d/py_calibration/py_calibration.html?highlight=findchessboardcorners
import numpy as np
import cv2
import matplotlib.image as mpimg
import glob
from PIL import Image
def calib():
"""
To get an undistorted image, we need camera matrix & distortion coefficient
Calculate them with 9*6 20 chessboard images
"""
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# Read in and make a list of calibration images
images = glob.glob('../lane_detection/camera_cal/src/calibration*.jpg')
# Array to store object points and image points from all the images
objpoints = [] # 3D points in real world space
imgpoints = [] # 2D points in image plane
# Prepare object points
objp = np.zeros((9* 6, 3), np.float32)#src and mah
objp[:, :2] = np.mgrid[0:6, 0:9].T.reshape(-1, 2) # x,y coordinates
for fname in images:
img = cv2.imread(fname)
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find the chessboard corners
ret, corners = cv2.findChessboardCorners(gray, (6,9), None)
# If corners are found, add object points, image points
if ret is True:
corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
imgpoints.append(corners2)
objpoints.append(objp)
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
return mtx, dist
def undistort(img, mtx, dist):
""" undistort image """
frame_undistorted = cv2.undistort(img, mtx, dist, None, mtx)
return frame_undistorted
参考:https://blog.csdn.net/firemicrocosm/article/details/48594897
注意标定的图片分辨率和后面使用的图片或视频分辨率相同