相机标定

# 相机标定

## 1、保存相机采集的图像

```
import cv2
cap = cv2.VideoCapture(0)
index = 0
while (1):
ret,frame = cap.read()
cv2.imshow("capture",frame)
 # ckey = cv2.waitKey(1)&0xFF
ckey = cv2.waitKey(1)
print(ckey)
if ret and (ckey == ord('s')):
# if ret:
# if ret and 0xFF == ord('q'):
# print(ckey)
index = index + 1
print(index)
cv2.imwrite('C:/Users/kangs/Desktop/calibration/' + str(index) + '.jpg',frame)
if index > 20:
    break
cap.release()
cv2.destroyAllWindows()
```

## 2、相机标定

```
# coding: utf-8
# Camera Calibration with OpenCV
# ### Run the code in the cell below to extract object points and image points for camera calibration.

import numpy as np
import cv2
import glob
import matplotlib
from scipy import io
matplotlib.use('qt5agg')
import matplotlib.pyplot as plt
np.set_printoptions(suppress=True)

# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((6*9,3), np.float32)
objp[:,:2] = np.mgrid[0:9, 0:6].T.reshape(-1,2)

# Arrays to store object points and image points from all the images.
objpoints = [] # 3d points in real world space
imgpoints = [] # 2d points in image plane.

# Make a list of calibration images
#images = glob.glob('calibration_wide/GO*.jpg')
images = glob.glob('iphoneX/*.jpg')
# Step through the list and search for chessboard corners
for idx, fname in enumerate(images):
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Find the chessboard corners
    ret, corners = cv2.findChessboardCorners(gray, (9,6), None)

    # If found, add object points, image points
    if ret == True:
        objpoints.append(objp)
        imgpoints.append(corners)

        # Draw and display the corners
        cv2.drawChessboardCorners(img, (9,6), corners, ret)
        cv2.imshow('img', img)
        cv2.waitKey(500)
cv2.destroyAllWindows()

# ### If the above cell ran sucessfully, you should now have `objpoints` and `imgpoints` needed for camera calibration.  Run the cell below to calibrate, calculate distortion coefficients, and test undistortion on an image!


import pickle

# Test undistortion on an image

img = cv2.imread('Mac/1.jpg')
img_size = (img.shape[1], img.shape[0])

# Do camera calibration given object points and image points
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_size,None,None)

dst = cv2.undistort(img, mtx, dist, None, mtx)

dist_pickle = {}
dist_pickle["mtx"] = mtx
dist_pickle["dist"] = dist
io.savemat('calibration.mat', {'calibration': dist_pickle})
np.savetxt("mtx.txt",mtx,fmt='%f',delimiter=",")
np.savetxt("dist.txt",dist,fmt='%f',delimiter=",")

#dst = cv2.cvtColor(dst, cv2.COLOR_BGR2RGB)
# Visualize undistortion
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10))
ax1.imshow(img)
ax1.set_title('Original Image', fontsize=30)
ax2.imshow(dst)
ax2.set_title('Undistorted Image', fontsize=30)
f.show()
print("success")
```

## 3、绘制棋盘格

```
import cv2
import numpy as np
# screen width height.length is the length of the every check board
width = 1824 
height = 2736
length = 304

image = np.zeros((width,height),dtype = np.uint8)
print(image.shape[0],image.shape[1])

for j in range(height):
    for i in range(width):
        if((int)(i/length) + (int)(j/length))%2:
            image[i,j] = 255;
cv2.imwrite("chess.jpg",image)
cv2.imshow("chess",image)
cv2.waitKey(0)
```

你可能感兴趣的:(算法)