运行#!/usr/bin/env python2.7 -- coding: UTF-8 -- import numpy as np import cv2 准备标定板参数 pattern = (9, 6) # 部角点数目 square_size = 25 # 每个棋盘格的边长(单位:毫米) 准备用于标定的图像路径(替换实际的图像路径) image_paths = [ 'pictures1.jpg', 'pictures2.jpg', 'pictures3.jpg', ] 创建存储角点和物体点的列表 obj_points = [] # 真实世界坐标点 img_points = [] # 图像平面角点 准备物体坐标 objp = np.zeros((pattern[0] * pattern[1], 3), np.float32) objp[:, :2] = np.mgrid[0:pattern[0], 0:pattern[1]].T.reshape(-1, 2) * square_size for image_path in image_paths: # 读取图像 img = cv2.imread(image_path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 查找角点 ret, corners = cv2.findChessboardCorners(gray, pattern, None) if ret: obj_points.append(objp) img_points.append(corners) 进行相机标定 ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, gray.shape[::-1], None, None) 打印相机内参和畸变参数 print("相机内参 (Camera Matrix):\n", mtx) print("\n畸变系数 (Distortion Coefficients):\n", dist) 保存相机参数 np.save("camera_matrix.npy", mtx) np.save("dist_coeffs.npy", dist) 后显示gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.error: /build/opencv-XDqSFW/opencv-3.2.0+dfsg/modules/imgproc/src/color.cpp:9748: error: (-215) scn == 3 || scn == 4 in function cvtColor 会报错是因为图片通道数并非4,更改代码使它先将图片通道数变为4然后运行上述代码要求的功能
时间: 2024-04-15 10:32:10 浏览: 121
grpc-python-demos
可以使用以下代码将图片通道数变为4,然后再运行标定相机的代码:
```python
import cv2
def convert_image_channels(image_path):
# 读取图片
image = cv2.imread(image_path)
# 检查图片通道数
channels = image.shape[2]
# 如果通道数不为4,则进行通道数改变
if channels != 4:
# 添加一个透明通道
image_with_alpha = cv2.cvtColor(image, cv2.COLOR_BGR2BGRA)
# 保存图片
cv2.imwrite('converted_image.png', image_with_alpha)
return 'converted_image.png'
else:
# 通道数已经是4,则无需改变
return image_path
# 准备标定板参数
pattern = (9, 6) # 棋盘格角点数目
square_size = 25 # 每个棋盘格边长(单位:毫米)
# 准备用于标定的图像路径(替换实际的图像路径)
image_paths = [
'pictures1.jpg',
'pictures2.jpg',
'pictures3.jpg',
]
# 创建存储角点和物体点的列表
obj_points = [] # 真实世界坐标点
img_points = [] # 图像平面角点
# 准备物体坐标
objp = np.zeros((pattern[0] * pattern[1], 3), np.float32)
objp[:, :2] = np.mgrid[0:pattern[0], 0:pattern[1]].T.reshape(-1, 2) * square_size
for image_path in image_paths:
# 将图片通道数变为4
converted_image_path = convert_image_channels(image_path)
# 读取图像
img = cv2.imread(converted_image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 查找角点
ret, corners = cv2.findChessboardCorners(gray, pattern, None)
if ret:
obj_points.append(objp)
img_points.append(corners)
# 进行相机标定
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, gray.shape[::-1], None, None)
# 打印相机内参和畸变参数
print("相机内参 (Camera Matrix):\n", mtx)
print("\n畸变系数 (Distortion Coefficients):\n", dist)
# 保存相机参数
np.save("camera_matrix.npy", mtx)
np.save("dist_coeffs.npy", dist)
```
上述代码在运行之前先调用 `convert_image_channels` 函数将图片的通道数改为4,并返回转换后的图片路径。然后再使用转换后的图片进行相机标定。
阅读全文