Python--Opencv工业广角相机图像畸变矫正

        实现畸变矫正之前需要知道两个重要参数,一个是相机内参,另一个是畸变参数。只有拿到这两个参数之后才可矫正,获取方式是通过标定来实现。

一.标定并获取重要参数

        标定不需要买标定板,只需要用一张白纸把下图打印出来,调整好大小噢

Python--Opencv工业广角相机图像畸变矫正_第1张图片

打印出来之后,用广角相机进行不同角度拍照,拍摄二十张图像即可。

        之后将20张图像传入下方代码,即可得到两个参数,我将其参数记录到txt文件内

import cv2
import numpy as np
import glob

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


objp = np.zeros((6 * 9, 3), np.float32)
objp[:, :2] = np.mgrid[0:9, 0:6].T.reshape(-1, 2)

obj_points = []  
img_points = []  

images = glob.glob("路径/*.png")
i = 0
for fname in images:
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)    
    size = gray.shape[::-1]

    ret, corners = cv2.findChessboardCorners(gray, (9, 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, (9, 6), corners, ret)  
        i += 1
        cv2.imwrite('conimg' + str(i) + '.jpg', img)


print(len(img_points))
cv2.destroyAllWindows()

ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, size, None, None)
with open('./log.txt','a') as f:
    print("ret:", ret)
    print("内参数矩阵mtx:\n", mtx)  
    print("畸变系数dist:\n", dist)  
    print("rvecs:\n", rvecs) 
    print("tvecs:\n", tvecs) 
    print(mtx,file = f)
    print(dist,file = f)

 得到参数

Python--Opencv工业广角相机图像畸变矫正_第2张图片

 二.畸变矫正

 将获取的参数带入下方代码中

import cv2
import numpy as np
import glob

def Correct(path,outpath):
 mtx = [[2.15206623e+03, 0.00000000e+00, 1.25097137e+03],
        [0.00000000e+00, 2.15359839e+03, 8.06536253e+02],
        [0.00000000e+00, 0.00000000e+00, 1.00000000e+00]]
 dist = [-3.05992261e-01, 2.19067370e-01, -2.37335833e-04, 2.43254582e-03, -1.65336735e-01]
 image_path = path
 img = cv2.imread(image_path)

 img_distort = cv2.undistort(img, np.array(mtx), np.array(dist))
 
 #---------------------------------------------------------------------------------
 
 cv2.imwrite(outpath, img_distort)
 

 return img_distort



if __name__ == "__main__":
 path = "图像路径"
 outpath = "输出路径"
 Correct(path,outpath)

你可能感兴趣的:(opencv,Python,图像,opencv,人工智能,计算机视觉)