├── distort.jpg ├── Chessboards ├── chessboard (01).jpg ├── chessboard (02).jpg ├── chessboard (03).jpg ├── chessboard (04).jpg ├── chessboard (05).jpg ├── chessboard (06).jpg ├── chessboard (07).jpg ├── chessboard (08).jpg ├── chessboard (09).jpg ├── chessboard (10).jpg ├── chessboard (11).jpg └── chessboard (12).jpg ├── README.md ├── image_correction.py ├── LICENSE ├── video_correction.py ├── .gitignore └── camera_calibrate.py /distort.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nebula4869/fisheye-camera-undistortion/HEAD/distort.jpg -------------------------------------------------------------------------------- /Chessboards/chessboard (01).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nebula4869/fisheye-camera-undistortion/HEAD/Chessboards/chessboard (01).jpg -------------------------------------------------------------------------------- /Chessboards/chessboard (02).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nebula4869/fisheye-camera-undistortion/HEAD/Chessboards/chessboard (02).jpg -------------------------------------------------------------------------------- /Chessboards/chessboard (03).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nebula4869/fisheye-camera-undistortion/HEAD/Chessboards/chessboard (03).jpg -------------------------------------------------------------------------------- /Chessboards/chessboard (04).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nebula4869/fisheye-camera-undistortion/HEAD/Chessboards/chessboard (04).jpg -------------------------------------------------------------------------------- /Chessboards/chessboard (05).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nebula4869/fisheye-camera-undistortion/HEAD/Chessboards/chessboard (05).jpg -------------------------------------------------------------------------------- /Chessboards/chessboard (06).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nebula4869/fisheye-camera-undistortion/HEAD/Chessboards/chessboard (06).jpg -------------------------------------------------------------------------------- /Chessboards/chessboard (07).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nebula4869/fisheye-camera-undistortion/HEAD/Chessboards/chessboard (07).jpg -------------------------------------------------------------------------------- /Chessboards/chessboard (08).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nebula4869/fisheye-camera-undistortion/HEAD/Chessboards/chessboard (08).jpg -------------------------------------------------------------------------------- /Chessboards/chessboard (09).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nebula4869/fisheye-camera-undistortion/HEAD/Chessboards/chessboard (09).jpg -------------------------------------------------------------------------------- /Chessboards/chessboard (10).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nebula4869/fisheye-camera-undistortion/HEAD/Chessboards/chessboard (10).jpg -------------------------------------------------------------------------------- /Chessboards/chessboard (11).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nebula4869/fisheye-camera-undistortion/HEAD/Chessboards/chessboard (11).jpg -------------------------------------------------------------------------------- /Chessboards/chessboard (12).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nebula4869/fisheye-camera-undistortion/HEAD/Chessboards/chessboard (12).jpg -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # fisheye-camera-undistortion 2 | Fisheye camera distortion correction based on opencv's chessboard calibration algorithm 3 | ### Environment 4 | 5 | - python==3.6.5 6 | - opencv-python==4.2.0 7 | 8 | 9 | ### Getting Started 10 | 11 | 1. Take several standard chessboard images with the fisheye lens to be corrected and placed into the 'Chessboards' folder (12 chessboard images taken with the lens used for the test image have been placed). 12 | 2. Run 'camera_calibrate.py' to calculate the internal parameter matrix K and the distortion coefficient vector D. 13 | 14 | 3. Run 'image_correction.py' to correct a single image captured by the camera. 15 | 16 | 4. Run 'video_correction.py' to correct the camera in real time. 17 | -------------------------------------------------------------------------------- /image_correction.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | 4 | 5 | def correct(img_in, k, d, dims): 6 | dim1 = img_in.shape[:2][::-1] 7 | assert dim1[0] / dim1[1] == dims[0] / dims[1], "Image to undistort needs to have same aspect ratio as the ones used in calibration" 8 | map1, map2 = cv2.fisheye.initUndistortRectifyMap(k, d, np.eye(3), k, dims, cv2.CV_16SC2) 9 | img_out = cv2.remap(img_in, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT) 10 | return img_out 11 | 12 | 13 | if __name__ == '__main__': 14 | Dims = tuple(np.load('./parameters/Dims.npy')) 15 | K = np.load('./parameters/K.npy') 16 | D = np.load('./parameters/D.npy') 17 | 18 | img = cv2.imread('distort.jpg') 19 | img = correct(img, k=K, d=D, dims=Dims) 20 | cv2.imshow('', img) 21 | cv2.imwrite('undistorted.jpg', img) 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Nebula4869 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /video_correction.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | 4 | 5 | def correct(img_in, k, d, dims): 6 | dim1 = img_in.shape[:2][::-1] 7 | assert dim1[0] / dim1[1] == dims[0] / dims[1], "Image to correct needs to have same aspect ratio as the ones used in calibration" 8 | map1, map2 = cv2.fisheye.initUndistortRectifyMap(k, d, np.eye(3), k, dims, cv2.CV_16SC2) 9 | img_out = cv2.remap(img_in, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT) 10 | return img_out 11 | 12 | 13 | if __name__ == '__main__': 14 | Dims = tuple(np.load('./parameters/Dims.npy')) 15 | K = np.load('./parameters/K.npy') 16 | D = np.load('./parameters/D.npy') 17 | 18 | cap = cv2.VideoCapture(0) 19 | cap.set(3, 1280) 20 | cap.set(4, 720) 21 | correct_flag = True 22 | while cap.isOpened(): 23 | _, frame = cap.read() 24 | if correct_flag: 25 | frame = correct(frame, k=K, d=D, dims=Dims) 26 | cv2.imshow('', frame) 27 | num_key = cv2.waitKey(1) 28 | if num_key == 13: 29 | correct_flag = not correct_flag 30 | if num_key == 27: 31 | break 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # Pycharm 132 | /.idea/* -------------------------------------------------------------------------------- /camera_calibrate.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | import os 4 | 5 | 6 | CHESSBOARD_SIZE = (6, 9) 7 | 8 | 9 | def calibrate(chessboard_path, show_chessboard=False): 10 | # Logical coordinates of chessboard corners 11 | obj_p = np.zeros((1, CHESSBOARD_SIZE[0] * CHESSBOARD_SIZE[1], 3), np.float32) 12 | obj_p[0, :, :2] = np.mgrid[0:CHESSBOARD_SIZE[0], 0:CHESSBOARD_SIZE[1]].T.reshape(-1, 2) 13 | 14 | obj_points = [] # 3d point in real world space 15 | img_points = [] # 2d points in image plane. 16 | 17 | # Iterate through all images in the folder 18 | image_list = os.listdir(chessboard_path) 19 | gray = None 20 | for image in image_list: 21 | img = cv2.imread(os.path.join(chessboard_path, image)) 22 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 23 | ret, corners = cv2.findChessboardCorners(gray, CHESSBOARD_SIZE, 24 | cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_FAST_CHECK + cv2.CALIB_CB_NORMALIZE_IMAGE) 25 | if ret: 26 | # Refining corners position with sub-pixels based algorithm 27 | obj_points.append(obj_p) 28 | cv2.cornerSubPix(gray, corners, (3, 3), (-1, -1), 29 | (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.01)) 30 | img_points.append(corners) 31 | print('Image ' + image + ' is valid for calibration') 32 | if show_chessboard: 33 | cv2.drawChessboardCorners(img, CHESSBOARD_SIZE, corners, ret) 34 | cv2.imwrite(os.path.join('./Chessboards_Corners', image), img) 35 | 36 | k = np.zeros((3, 3)) 37 | d = np.zeros((4, 1)) 38 | dims = gray.shape[::-1] 39 | num_valid_img = len(obj_points) 40 | if num_valid_img > 0: 41 | rvecs = [np.zeros((1, 1, 3), dtype=np.float64) for _ in range(num_valid_img)] 42 | tvecs = [np.zeros((1, 1, 3), dtype=np.float64) for _ in range(num_valid_img)] 43 | rms, _, _, _, _ = cv2.fisheye.calibrate(obj_points, img_points, gray.shape[::-1], k, d, rvecs, tvecs, 44 | # cv2.fisheye.CALIB_CHECK_COND + 45 | # When CALIB_CHECK_COND is set, the algorithm checks if the detected corners of each images are valid. 46 | # If not, an exception is thrown which indicates the zero-based index of the invalid image. 47 | # Such image should be replaced or removed from the calibration dataset to ensure a good calibration. 48 | cv2.fisheye.CALIB_RECOMPUTE_EXTRINSIC + 49 | cv2.fisheye.CALIB_FIX_SKEW, 50 | (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-6)) 51 | print("Found " + str(num_valid_img) + " valid images for calibration") 52 | return k, d, dims 53 | 54 | 55 | if __name__ == '__main__': 56 | if not os.path.exists('./parameters'): 57 | os.makedirs('./parameters') 58 | if not os.path.exists('./Chessboards_Corners'): 59 | os.makedirs('./Chessboards_Corners') 60 | 61 | K, D, Dims = calibrate('./Chessboards', show_chessboard=True) 62 | np.save('./parameters/Dims', np.array(Dims)) 63 | np.save('./parameters/K', np.array(K)) 64 | np.save('./parameters/D', np.array(D)) 65 | --------------------------------------------------------------------------------