python opencv标定相机

∥☆過路亽.° 提交于 2019-12-03 07:11:10

1.采集好图片。30张这样就足够了,图片需有不同大小不同位置,且一定要清晰,模糊的角点图影响判断。

2.通过程序得到内参同时做畸形校正

# -*- coding:utf-8 -*-
#!/usr/bin/env python
__author__ = 'Huaqing'
import numpy as np
import cv2, copy, math, sys
import glob

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


objp = np.zeros((BOARD_SIZE[0]*BOARD_SIZE[1],3), np.float32)
objp[:,:2] = np.mgrid[0:BOARD_SIZE[0],0:BOARD_SIZE[1]].T.reshape(-1,2)
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.


images = glob.glob('camera_calib/images/'+ '/*.jpg')
i = 1
for fname in images:
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, corners = cv2.findChessboardCorners(gray, BOARD_SIZE, None)
    if ret == True:
        objpoints.append(objp)
        bak = copy.copy(corners)
        cv2.cornerSubPix(gray, corners, (11,11), (-1,-1), criteria)
        #print np.max(bak - corners)
        imgpoints.append(corners)

        cv2.drawChessboardCorners(img, BOARD_SIZE, corners, ret)
        cv2.imshow(fname, img)
        cv2.waitKey(10)

cv2.destroyAllWindows()

print "------------------求解mtx,dist-------------------"
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None, flags=cv2.CALIB_FIX_K3)
print "mtx:",mtx
print "dist",dist
# 畸变校正
img = cv2.imread("camera_calib/images/6634.jpg")
h, w = img.shape[:2]
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))
print "------------------使用undistort函数进行畸变校正并保存为calibresult.jpg-------------------" 
dst = cv2.undistort(img,mtx,dist,None,newcameramtx)
#dst1 = dst[y:y+h,x:x+w]
cv2.imwrite('calibresult.jpg', dst)
print "校正完成!"



 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!