Created
October 31, 2022 00:07
-
-
Save zhuker/1d0b7a98b6f56afa831a5f041bac3439 to your computer and use it in GitHub Desktop.
Calibrate camera
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import cv2 as cv | |
import glob | |
path_to_images = './dji-mini2/*.JPG' | |
draw_ui = False | |
def calibrate(): | |
# 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) | |
gW = 9 # 7 | |
gH = 7 # 6 | |
objp = np.zeros((gH * gW, 3), np.float32) | |
objp[:, :2] = np.mgrid[0:gW, 0:gH].T.reshape(-1, 2) | |
objp = objp * 21 | |
# 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(path_to_images) | |
if draw_ui: | |
# Create a Named Window | |
cv.namedWindow('win_name', cv.WINDOW_NORMAL) | |
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, (gW, gH), 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(corners2) | |
if draw_ui: | |
# Draw and display the corners | |
cv.drawChessboardCorners(img, (gW, gH), corners2, ret) | |
# Show the Image in the Window | |
cv.imshow('win_name', img) | |
# Resize the Window | |
cv.resizeWindow('win_name', 1920, 1080) | |
cv.waitKey(500) | |
(h, w) = gray.shape | |
ret, mtx, dist, rvecs, tvecs = cv.calibrateCamera(objpoints, imgpoints, (w, h), None, None) | |
print(mtx) | |
if draw_ui: | |
cv.destroyAllWindows() | |
return mtx | |
calibrate() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment