相機標定(camera calibration )

在opencv中提供了一組函數用於實現相機的標定,標定返回的值包括:相機內參矩陣(fx fy xc yc)、相機外參矩陣(R t)以及畸變矩陣。python

標定的步驟以下:git

1. 準備棋盤格,棋盤格圖片能夠自行打印,如下使用10*7方格的棋盤格,交點則爲9*6,棋盤格的大小1mm,即 gridsize=1github

2. 拍照,拍照的原則是多角度,根據理論至少要兩種角度的拍照,實際中一般會拍20張左右;app

3. 使用opencv提供的角點檢測函數findChessboardCorners找到棋盤格中的角點,並將每幅圖片的角點值存放到list中,同時將棋盤格的角點的三維座標存放到另外一個list。函數

4. 使用calibrateCamera函數獲取內存矩陣、畸變矩陣、旋轉矩陣以及轉移矩陣。code

5.使用undistort函數將畸變的圖像進行校訂並查看校訂後的圖片效果。圖片

代碼以下(opencv_3.4.3):內存

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 16 08:45:25 2019

@author: hmeng
"""

import numpy as np
import cv2

#圖片角點個數
objp_dict = {
	1: (9, 5),
	2: (9, 6),
	3: (9, 6),
	4: (9, 6),
	5: (9, 6),
	6: (9, 6),
	7: (9, 6),
	8: (9, 6),
	9: (9, 6),
	10: (9, 6),
	11: (9, 6),
	12: (9, 6),
	13: (9, 6),
	14: (9, 6),
	15: (9, 6),
	16: (9, 6),
	18: (9, 6),
	17: (9, 6),
	19: (9, 6),
	20: (9, 6),
}

objp_list = []
corners_list = []

for k in objp_dict:
    nx, ny = objp_dict[k]
    
	# Prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) gridsize=1(mm)
    objp = np.zeros((nx*ny,3), np.float32)
    #生成角點的三維座標
    objp[:,:2] = np.mgrid[0:nx, 0:ny].T.reshape(-1,2)
	# Make a list of calibration images
    fname = 'camera_cal/calibration%s.jpg' % str(k)
    img = cv2.imread(fname)

	# Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

	# Find the chessboard corners
    ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)

	# If found, save & draw corners
    if ret == True:
        # Save object points and corresponding corners
        objp_list.append(objp)
        corners_list.append(corners)
		# Draw and display the corners
		#cv2.drawChessboardCorners(img, (nx, ny), corners, ret)
		#plt.imshow(img)
		#plt.show()
		#print('Found corners for %s' % fname)
    else:
        print('Warning: ret = %s for %s' % (ret, fname))
            
img = cv2.imread('camera_cal/calibration1.jpg')
img_size = (img.shape[1], img.shape[0])
'''
mtx : 內參矩陣
dist: 畸變矩陣
rvecs : 旋轉矩陣
tvecs : 轉移矩陣
'''
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objp_list, corners_list, img_size,None,None)

#將原始圖片轉換成未發生畸變的圖片
dst = cv2.undistort(img, mtx, dist, None, mtx)
com_img = np.hstack((img, dst))
cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.imshow('image', com_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

代碼以及使用到的圖片見github:utf-8

https://github.com/JosiahMg/calibrateCamerait

相關文章
相關標籤/搜索