forked from benmattison/Zaber479
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcameraRectify.py
More file actions
53 lines (38 loc) · 1.58 KB
/
cameraRectify.py
File metadata and controls
53 lines (38 loc) · 1.58 KB
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
import numpy as np
import cv2
import glob
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((7 * 9, 3), np.float32)
objp[:, :2] = np.mgrid[0:9, 0:7].T.reshape(-1, 2)
# 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('StereoCalibration/Left/*.jpg')
for fname in images:
#read image from StereoCalibration folder
img = cv2.imread(fname)
# Convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#find chessboard corners
ret, corners = cv2.findChessboardCorners(gray, (9, 7), None)
#showing if it read the picture properly
print(ret)
if ret == True:
objpoints.append(objp)
corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
imgpoints.append(corners)
# Calibrate camera
ret, cameraMatrix, distCoeffs, rvecs, tvecs, = cv2.calibrateCamera(objpoints,imgpoints,gray.shape[::-1],None,None)
# Get new camera matrix
img = cv2.imread('StereoCalibration/Left/StereoLeft_0.jpg')
h,w = img.shape[:2]
newCameraMatrix, roi = cv2.getOptimalNewCameraMatrix(cameraMatrix,distCoeffs,(w,h),1,(w,h))
# Undistort
undistorted = cv2.undistort(img, cameraMatrix, distCoeffs, None, newCameraMatrix)
#crop image, needs tweeking
#x,y,w,h = roi
#undistorted = undistorted[y:y+h, x:x+h]
#write undistorted test image
cv2.imwrite('StereoCalibration/Left/randomPicCali.jpg',undistorted)