Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/CameraCalibration/cameraCalibration.py
3118 views
1
#!/usr/bin/env python
2
3
import cv2
4
import numpy as np
5
import os
6
import glob
7
8
# Defining the dimensions of checkerboard
9
CHECKERBOARD = (6,9)
10
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
11
12
# Creating vector to store vectors of 3D points for each checkerboard image
13
objpoints = []
14
# Creating vector to store vectors of 2D points for each checkerboard image
15
imgpoints = []
16
17
18
# Defining the world coordinates for 3D points
19
objp = np.zeros((1, CHECKERBOARD[0]*CHECKERBOARD[1], 3), np.float32)
20
objp[0,:,:2] = np.mgrid[0:CHECKERBOARD[0], 0:CHECKERBOARD[1]].T.reshape(-1, 2)
21
prev_img_shape = None
22
23
# Extracting path of individual image stored in a given directory
24
images = glob.glob('./images/*.jpg')
25
for fname in images:
26
img = cv2.imread(fname)
27
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
28
# Find the chess board corners
29
# If desired number of corners are found in the image then ret = true
30
ret, corners = cv2.findChessboardCorners(gray, CHECKERBOARD, cv2.CALIB_CB_ADAPTIVE_THRESH+
31
cv2.CALIB_CB_FAST_CHECK+cv2.CALIB_CB_NORMALIZE_IMAGE)
32
33
"""
34
If desired number of corner are detected,
35
we refine the pixel coordinates and display
36
them on the images of checker board
37
"""
38
if ret == True:
39
objpoints.append(objp)
40
# refining pixel coordinates for given 2d points.
41
corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
42
43
imgpoints.append(corners2)
44
45
# Draw and display the corners
46
img = cv2.drawChessboardCorners(img, CHECKERBOARD, corners2,ret)
47
48
cv2.imshow('img',img)
49
cv2.waitKey(0)
50
51
cv2.destroyAllWindows()
52
53
h,w = img.shape[:2]
54
55
"""
56
Performing camera calibration by
57
passing the value of known 3D points (objpoints)
58
and corresponding pixel coordinates of the
59
detected corners (imgpoints)
60
"""
61
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
62
63
print("Camera matrix : \n")
64
print(mtx)
65
print("dist : \n")
66
print(dist)
67
print("rvecs : \n")
68
print(rvecs)
69
print("tvecs : \n")
70
print(tvecs)
71
72