1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| import numpy as np import cv2 as cv import glob
criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30, 0.001)
objp = np.zeros((6*9, 3), np.float32) objp[:,:2] = np.mgrid[0:9, 0:6].T.reshape(-1,2)
objpoints = [] imgpoints = []
images = glob.glob('chessboard/*.jpg')
for fname in images: img = cv.imread(fname) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
ret, corners = cv.findChessboardCorners(gray, (9,6),None)
if ret == True: objpoints.append(objp) corners2 = cv.cornerSubPix(gray, corners, (11,11),(-1,-1),criteria) imgpoints.append(corners2)
cv.drawChessboardCorners(img,(9,6),corners2,ret) cv.imshow('img', img) cv.waitKey(500)
ret, mtx, dist, rvecs, tvecs = cv.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
np.savez('cameracalib',mtx=mtx, dist=dist, rvecs=rvecs, tvecs=tvecs) calib_file = np.load('cameracalib.npz') print(calib_file['mtx'])
img = cv.imread('chessboard/left12.jpg') h, w = img.shape[:2] newcameramtx, roi = cv.getOptimalNewCameraMatrix(calib_file['mtx'], calib_file['dist'], (w,h), 1, (w,h))
dst = cv.undistort(img,mtx, dist, None, newcameramtx) x,y,w,h = roi dst1 = dst[y:y+h, x:x+w] cv.imshow('ds1',dst1) cv.imwrite('calibresult.png', dst1)
mapx, mapy = cv.initUndistortRectifyMap(mtx, dist, None, newcameramtx, (w,h), 5) dst2 = cv.remap(img, mapx, mapy, cv.INTER_LINEAR) dst2 = dst2[y:y+h, x:x+w] cv.imshow('ds2',dst2)
cv.waitKey(0) cv.destroyAllWindows()
|