用opencv-python写一个九点标定程序
时间: 2023-09-09 15:10:31 浏览: 268
好的,以下是一个简单的九点标定程序:
首先,导入必要的库:
```python
import cv2
import numpy as np
```
然后,定义标定板的规格和大小:
```python
# 标定板规格
ROWS = 9
COLS = 9
# 标定板大小
SIZE = 20 # 单位为毫米
```
接下来,定义一个函数来生成标定板的三维坐标:
```python
def generate_3D_points():
points = np.zeros((ROWS * COLS, 3), np.float32)
points[:,:2] = np.mgrid[0:ROWS, 0:COLS].T.reshape(-1, 2)
return points * SIZE
```
然后,我们需要读取标定板的图像并检测角点:
```python
# 读取标定板图像
img = cv2.imread('calibration_board.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 检测角点
ret, corners = cv2.findChessboardCorners(gray, (ROWS, COLS), None)
```
如果成功检测到角点,我们可以继续进行标定:
```python
if ret == True:
# 优化角点位置
corners = cv2.cornerSubPix(gray, corners, (11,11), (-1,-1), criteria)
# 生成标定板的三维坐标
obj_points = generate_3D_points()
# 标定相机
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera([obj_points], [corners], gray.shape[::-1], None, None)
```
最后,我们可以使用标定结果来校正图像:
```python
# 校正图像
dst = cv2.undistort(img, mtx, dist, None, mtx)
```
完整代码如下:
```python
import cv2
import numpy as np
# 标定板规格
ROWS = 9
COLS = 9
# 标定板大小
SIZE = 20 # 单位为毫米
# 生成标定板的三维坐标
def generate_3D_points():
points = np.zeros((ROWS * COLS, 3), np.float32)
points[:,:2] = np.mgrid[0:ROWS, 0:COLS].T.reshape(-1, 2)
return points * SIZE
# 读取标定板图像并检测角点
img = cv2.imread('calibration_board.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(gray, (ROWS, COLS), None)
if ret == True:
# 优化角点位置
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
corners = cv2.cornerSubPix(gray, corners, (11,11), (-1,-1), criteria)
# 生成标定板的三维坐标
obj_points = generate_3D_points()
# 标定相机
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera([obj_points], [corners], gray.shape[::-1], None, None)
# 校正图像
dst = cv2.undistort(img, mtx, dist, None, mtx)
cv2.imshow('dst', dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
else:
print('角点检测失败')
```
阅读全文