赞
踩
接上篇文章:【鱼眼+普通相机】相机标定
附代码:
使用cv2.undistort
""" Create May 11, 2024 @author Wang Jiajun """ import cv2 import numpy as np def 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,k3 resolution = 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 np def 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,k3 resolution = 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, map2 if __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()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。