import os
import sys
import cv2
import shutil
import numpy as np
ImgPath = input("Please enter the path where the JPG is located: ") + '/'
Savepath = '/home/moonx/Desktop/undistorted_pictures/'
fx = 1990.992014
cx = 911.5402
fy = 1993.371404
cy = 603.671151
k1, k2, p1, p2, k3 = -0.551182, 0.289106, 0.000385, -0.001226, 0.0
#相机坐标系到像素坐标系的转换矩阵
k = np.array([
[fx, 0, cx],
[0, fy, cy],
[0, 0, 1]
])
#畸变系数
d = np.array([
k1, k2, p1, p2, k3
])
#璜老板的三行去畸变
def undistort(img):
h, w = img.shape[:2]
mapx, mapy = cv2.initUndistortRectifyMap(k, d, None, k, (w, h), 5)
return cv2.remap(img, mapx, mapy, cv2.INTER_LINEAR)
os.mkdir(Savepath)
print('\n' + 'Dictory /home/moonx/Desktop/annotated_pictures/ has been created!' + '\n')
imagelist = os.listdir(ImgPath)
for image in imagelist:
img = ImgPath + image
print(img)
img = cv2.imread(img)
img = undistort(img)
cv2.imwrite(Savepath+image, img)
升级版
#!/usr/bin/env python
import cv2
import shutil
import numpy as np
import yaml
import argparse
import os
########################
parser = argparse.ArgumentParser()
parser.add_argument("--image_dir_path", type=str, default='calibrationdata')
parser.add_argument("--undistorted_image_dir_path", type=str, default='undistorted')
parser.add_argument("--intrinsics_file_path", type=str, default='test.yaml')
args = parser.parse_args()
########################
def load_yaml_file(file_path):
with open(file_path, 'r') as f:
ret = yaml.safe_load(f.read())
return ret
########################
def load_intrinsics(yaml_path):
params = load_yaml_file(yaml_path)
k = np.array(params['K']).reshape(3, 3)
d = np.array(params['D'])
return k, d
########################
def undistort(img, k, d):
h, w = img.shape[:2]
mapx, mapy = cv2.initUndistortRectifyMap(k, d, None, k, (w, h), 5)
return cv2.remap(img, mapx, mapy, cv2.INTER_LINEAR)
########################
def main():
k, d = load_intrinsics(args.intrinsics_file_path)
image_name_list = os.listdir(args.image_dir_path)
image_path_list = [os.path.join(args.image_dir_path, x) for x in image_name_list]
for image_path in image_path_list:
print(image_path)
image = cv2.imread(image_path)
image = undistort(image, k, d)
undistorted_image_path = image_path.replace(args.image_dir_path, args.undistorted_image_dir_path)
cv2.imwrite(undistorted_image_path, image)
########################
if __name__ == '__main__':
main()
intrinsics yaml
header:
seq: 313
stamp:
secs: 33051
nsecs: 670597000
frame_id: usb_cam
height: 1080
width: 1920
distortion_model: plumb_bob
D: [-0.567029, 0.291274, 0.006039, 0.002272, 0.000000]
K: [2003.097697, 0.000000, 937.207244, 0.000000, 1999.234506, 484.602893, 0.000000, 0.000000, 1.000000]
R: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]
P: [1750.765991, 0.0, 961.122152, 0.0, 0.0, 1979.051758, 506.167732, 0.0, 0.0, 0.0, 1.0, 0.0]
binning_x: 0
binning_y: 0
roi:
x_offset: 0
y_offset: 0
height: 0
width: 0
do_rectify: False