python opencv 拍照_摄像头标定 Python + OpenCV

〇、基础

一些单孔摄像机(照相机)会给图像带来很多畸变。畸变主要有两种:径向畸变和切向畸变。如下图所示,用红色直线将棋盘的两个边标注出来,但是你会发现棋盘的边界并不和红线重合,这就是畸变的体现。

23928a80fa0f

1.png

在3D相关应用中,必须要先校正这些畸变。在此文档中,我们使用棋盘格对摄像头畸变进行校正。

Tips:

软件环境:

python 2.7.12 + OpenCV (OpenCV2和OpenCV3皆适用)

校正使用的图片为摄像头预先拍摄好的图片。

一、设置

为了找到棋盘的图案,我们要使用函数 cv2.findChessboardCorners()。我们还需要传入图案的类型,比如说 8x8 的格子或 5x5 的格子等。在本例中我们使用的是 7x8 的格子。(通常情况下棋盘都是 8x8 或者 7x7)。它会返回角点,如果得到图像的话返回值类型(Retval)就会是 True。这些角点会按顺序排列(从左到右,从上到下)。

这个函数可能不会找出所有图像中应有的图案。所以一个好的方法是编写代码,启动摄像机并在每一帧中检查是否有应有的图案。在我们获得图案之后我们要找到角点并把它们保存成一个列表。在读取下一帧图像之前要设置一定的间隔,这样我们就有足够的时间调整棋盘的方向。

除了使用棋盘之外,我们还可以使用环形格子,但是要使用函数cv2.findCirclesGrid() 来找图案。据说使用环形格子只需要很少的图像就可以了。

在找到这些角点之后我们可以使用函数 cv2.cornerSubPix() 增加准确度。我们使用函数 cv2.drawChessboardCorners() 绘制图案。所有的这些步骤都被包含在下面的代码中了:

import numpy as np

import cv2

import glob

# 设置寻找亚像素角点的参数,采用的停止准则是最大循环次数30和最大误差容限0.001

criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)

# 获取标定板角点的位置

objp = np.zeros((6*7,3), np.float32) # 7x8的格子 此处参数根据使用棋盘格规格进行修改

objp[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2)

# 将世界坐标系建在标定板上,所有点的Z坐标全部为0,所以只需要赋值x和y

objpoints = [] # 存储3D点

imgpoints = [] # 存储2D点

images = glob.glob('*.jpg') # 文件存储路径,存储需要标定的摄像头拍摄的棋盘格图片

for fname in images:

img = cv2.imread(fname)

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

size = gray.shape[::-1]

# 寻找棋盘格角点

ret, corners = cv2.findChessboardCorners(gray, (7,6),None)

if ret == True:

objpoints.append(objp)

# 在原角点的基础上寻找亚像素角点

corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)

if corners2.any():

img_points.append(corners2)

else:

img_points.append(corners)

# 绘制角点并显示

img = cv2.drawChessboardCorners(img, (7,6), corners2,ret)

cv2.imshow('img',img)

cv2.waitKey(500)

cv2.destroyAllWindows()

一幅图像和被绘制在上面的图案:

23928a80fa0f

2.png

二、标定

在得到了这些对象点和图像点之后,我们已经准备好来做摄像机标定了。

我们要使用的函数是 cv2.calibrateCamera()。它会返回摄像机矩阵,畸变系数,旋转和变换向量等。

ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)

三、畸变校正

现在我们找到我们想要的东西了,我们可以找到一幅图像来对他进行校正了。OpenCV 提供了两种方法,我们都学习一下。不过在那之前我们可以使用从函数 cv2.getOptimalNewCameraMatrix() 得到的自由缩放系数对摄像机矩阵进行优化。如果缩放系数 alpha = 0,返回的非畸变图像会带有最少量的不想要的像素。它甚至有可能在图像角点去除一些像素。如果 alpha = 1,所有的像素都会被返回,还有一些黑图像。它还会返回一个 ROI 图像,我们可以用来对结果进行裁剪。

我们读取一张新的图像images[12](为摄像头拍摄图片中的一张)

img = cv2.imread(images[12])

h, w = img.shape[:2]

newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))

1、使用undistort函数

使用 cv2.undistort() 这是最简单的方法。只需使用这个函数和上边得到的 ROI 对结果进行裁剪。

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

x,y,w,h = roi

dst = dst[y:y+h, x:x+w]

cv2.imwrite('calibresult11.png',dst)

print "方法一:dst的大小为:", dst1.shape

2、使用重映射的方式

使用 remapping 这应该属于“曲线救国”了。首先我们要找到从畸变图像到非畸变图像的映射方程。再使用重映射方程。

# 获取映射方程

mapx,mapy = cv2.initUndistortRectifyMap(mtx,dist,None,newcameramtx,(w,h),5)

dst = cv2.remap(img,mapx,mapy,cv2.INTER_LINEAR) # 重映射

# dst = cv2.remap(img,mapx,mapy,cv2.INTER_CUBIC) # 使用此参数,图像变小

x,y,w,h = roi

dst2 = dst[y:y+h,x:x+w]

cv2.imwrite('calibresult11_2.jpg', dst2)

print "方法二:dst的大小为:", dst2.shape

这两中方法给出的结果是相同的。结果如下所示,此时图像中的所有边界都变直了。

23928a80fa0f

3.png

四、反向投影误差

我们可以利用反向投影误差对我们找到的参数的准确性进行估计。得到的结果越接近 0 越好。有了内部参数,畸变参数和旋转变换矩阵,我们就可以使用 cv2.projectPoints() 将对象点转换到图像点。然后就可以计算变换得到图像与角点检测算法的绝对差了。然后我们计算所有标定图像的误差平均值。

tot_error = 0

for i in xrange(len(obj_points)):

img_points2, _ = cv2.projectPoints(obj_points[i],rvecs[i],tvecs[i],mtx,dist)

error = cv2.norm(img_points[i],img_points2, cv2.NORM_L2)/len(img_points2)

tot_error += error

mean_error = tot_error/len(obj_points)

print "total error: ", tot_error

print "mean error: ", mean_error

五、代码

# -*- coding:utf-8 -*-

__author__ = 'Microcosm'

import cv2

import numpy as np

import glob

# 设置寻找亚像素角点的参数,采用的停止准则是最大循环次数30和最大误差容限0.001

criteria = (cv2.TERM_CRITERIA_MAX_ITER | cv2.TERM_CRITERIA_EPS, 30, 0.001)

# 获取标定板角点的位置

objp = np.zeros((6*7,3), np.float32)

objp[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2) # 将世界坐标系建在标定板上,所有点的Z坐标全部为0,所以只需要赋值x和y

obj_points = [] # 存储3D点

img_points = [] # 存储2D点

images = glob.glob("*.jpg")

for fname in images:

img = cv2.imread(fname)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

size = gray.shape[::-1]

ret, corners = cv2.findChessboardCorners(gray, (7,6), None)

if ret:

obj_points.append(objp)

corners2 = cv2.cornerSubPix(gray, corners, (5,5), (-1,-1), criteria) # 在原角点的基础上寻找亚像素角点

if corners2.any():

img_points.append(corners2)

else:

img_points.append(corners)

cv2.drawChessboardCorners(img, (7,6), corners, ret)

cv2.imshow('img', img)

cv2.waitKey(0)

print len(img_points)

cv2.destroyAllWindows()

# 标定

ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points,size, None, None)

print "ret:",ret

print "mtx:\n",mtx # 内参数矩阵

print "dist:\n",dist # 畸变系数 distortion cofficients = (k_1,k_2,p_1,p_2,k_3)

print "rvecs:\n",rvecs # 旋转向量 # 外参数

print "tvecs:\n",tvecs # 平移向量 # 外参数

print("-----------------------------------------------------")

# 畸变校正

img = cv2.imread(images[12])

h, w = img.shape[:2]

newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))

print newcameramtx

print("------------------使用undistort函数-------------------")

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

x,y,w,h = roi

dst1 = dst[y:y+h,x:x+w]

cv2.imwrite('calibresult11.jpg', dst1)

print "方法一:dst的大小为:", dst1.shape

# undistort方法二

print("-------------------使用重映射的方式-----------------------")

mapx,mapy = cv2.initUndistortRectifyMap(mtx,dist,None,newcameramtx,(w,h),5) # 获取映射方程

#dst = cv2.remap(img,mapx,mapy,cv2.INTER_LINEAR) # 重映射

dst = cv2.remap(img,mapx,mapy,cv2.INTER_CUBIC) # 重映射后,图像变小了

x,y,w,h = roi

dst2 = dst[y:y+h,x:x+w]

cv2.imwrite('calibresult11_2.jpg', dst2)

print "方法二:dst的大小为:", dst2.shape # 图像比方法一的小

print("-------------------计算反向投影误差-----------------------")

tot_error = 0

for i in xrange(len(obj_points)):

img_points2, _ = cv2.projectPoints(obj_points[i],rvecs[i],tvecs[i],mtx,dist)

error = cv2.norm(img_points[i],img_points2, cv2.NORM_L2)/len(img_points2)

tot_error += error

mean_error = tot_error/len(obj_points)

print "total error: ", tot_error

print "mean error: ", mean_error

参考文档:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值