本文主要是介绍【图像畸变校正】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
接上篇文章:【鱼眼+普通相机】相机标定
附代码:
方法一:
使用cv2.undistort
"""Create May 11, 2024@author Wang Jiajun
"""import cv2
import numpy as npdef correct(img,camera_file='E:/calib_yaml/ship_calib.yaml'):"""矫正图像,去除畸变img: 输入图像camera_file: 相机参数文件return: 矫正后的图像"""fs = cv2.FileStorage(camera_file, cv2.FILE_STORAGE_READ)camera_matrix = fs.getNode("camera_matrix").mat()dist_coeffs = fs.getNode("dist_coeffs").mat() # 畸变参数--顺序很重要!!!:k1,k2,p1,p2,k3resolution = fs.getNode("resolution").mat() # 图像分辨率imSize = (resolution[0][0], resolution[1][0])fs.release()# 矫正图像img_distort = cv2.undistort(img, np.array(camera_matrix), np.array(dist_coeffs))return img_distort if __name__ == '__main__':camera_file = 'E:/calib_yaml/ship_calib.yaml'video = cv2.VideoCapture(0)while True:ret, img = video.read()# 3. 矫正图像img = cv2.resize(img, (640, 480))cv2.putText(img, "Press q to exit", (20, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 200, 0), 2)img_distort = cv2.correct(img, camera_file )# 4. 显示原图和矫正后的图像cv2.imshow('img_original', img)cv2.imshow('img_distort', img_distort)key = cv2.waitKey(1)# 5. 按q退出if key & 0xFF == ord('q'):break# 6. 关闭窗口video.release()cv2.destroyAllWindows()
方法二:
使用cv2.initUndistortRectifyMap建立映射关系,就不用每次读取内参了,速度更快。
"""Create May 11, 2024@author Wang Jiajun
"""import cv2
import numpy as npdef correct(camera_file='E:/calib_yaml/ship_calib.yaml'):"""矫正图像,去除畸变img: 输入图像camera_file: 相机参数文件return: 矫正后的图像"""fs = cv2.FileStorage(camera_file, cv2.FILE_STORAGE_READ)camera_matrix = fs.getNode("camera_matrix").mat()dist_coeffs = fs.getNode("dist_coeffs").mat() # 畸变参数--顺序很重要!!!:k1,k2,p1,p2,k3resolution = fs.getNode("resolution").mat() # 图像分辨率imSize = (resolution[0][0], resolution[1][0])fs.release()# 矫正图像new_camera_matrix, roi = cv2.getOptimalNewCameraMatrix(np.array(camera_matrix), np.array(dist_coeffs),imSize, 0,imSize)map1, map2 = cv2.initUndistortRectifyMap(np.array(camera_matrix), np.array(dist_coeffs), None, new_camera_matrix,imSize, cv2.CV_32FC1)# img_distort = cv2.undistort(img, np.array(camera_matrix), np.array(dist_coeffs))return map1, map2if __name__ == '__main__':camera_file = 'E:/calib_yaml/ship_calib.yaml'map1, map2 = correct(camera_file)video = cv2.VideoCapture(0)while True:ret, img = video.read()# 3. 矫正图像img = cv2.resize(img, (640, 480))cv2.putText(img, "Press q to exit", (20, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 200, 0), 2)img_distort = cv2.remap(img, map1, map2, cv2.INTER_LINEAR)# 4. 显示原图和矫正后的图像cv2.imshow('img_original', img)cv2.imshow('img_distort', img_distort)key = cv2.waitKey(1)# 5. 按q退出if key & 0xFF == ord('q'):break# 6. 关闭窗口video.release()cv2.destroyAllWindows()
这篇关于【图像畸变校正】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!