Fisheye lens correction

Fisheye lens correction

Introduction

Since the drone used in the research is a fisheye lens, it became necessary to correct the acquired image.

From reference [1], the general correction seems to be rectilinear correction, and it seems that it can be done with opencv, so I touched it.

Environment

python's opencv module cv2 does not have a fisheye lens calibration module

Therefore, build the environment of ʻopencv c ++`.

But there was a person who was doing it with ʻopen cv3 series`, so I did it there. See [4]

Copy the checkered pattern required for calibration with A4.

チェッカーボード-1024x717.png

Take a checkered pattern from various angles with a fisheye camera (about 20 shots).

Run

calibration.py


import cv2
# assert cv2.__version__[0] == '3', 'The fisheye module requires opencv version >= 3.0.0'
import numpy as np
import os
import glob

CHECKERBOARD = (6,9)

print(CHECKERBOARD)
subpix_criteria = (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER, 30, 0.1)
calibration_flags = cv2.fisheye.CALIB_RECOMPUTE_EXTRINSIC+cv2.fisheye.CALIB_CHECK_COND+cv2.fisheye.CALIB_FIX_SKEW
objp = np.zeros((1, CHECKERBOARD[0]*CHECKERBOARD[1], 3), np.float32)
objp[0,:,:2] = np.mgrid[0:CHECKERBOARD[0], 0:CHECKERBOARD[1]].T.reshape(-1, 2)
_img_shape = None
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.
images = glob.glob('source/*.jpg')
for fname in images:
    img = cv2.imread(fname)
    if _img_shape == None:
        _img_shape = img.shape[:2]
    else:
        assert _img_shape == img.shape[:2], "All images must share the same size."
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    # Find the chess board corners
    ret, corners = cv2.findChessboardCorners(gray, CHECKERBOARD, cv2.CALIB_CB_ADAPTIVE_THRESH+cv2.CALIB_CB_FAST_CHECK+cv2.CALIB_CB_NORMALIZE_IMAGE)
    # If found, add object points, image points (after refining them)
    if ret == True:
        objpoints.append(objp)
        cv2.cornerSubPix(gray,corners,(3,3),(-1,-1),subpix_criteria)
        imgpoints.append(corners)

print('img end')
N_OK = len(objpoints)
K = np.zeros((3, 3))
D = np.zeros((4, 1))
rvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)]
tvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)]
rms, _, _, _, _ = \
    cv2.fisheye.calibrate(
        objpoints,
        imgpoints,
        gray.shape[::-1],
        K,
        D,
        rvecs,
        tvecs,
        calibration_flags,
        (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-6)
    )
print("Found " + str(N_OK) + " valid images for calibration")
print("DIM=" + str(_img_shape[::-1]))
print("K=np.array(" + str(K.tolist()) + ")")
print("D=np.array(" + str(D.tolist()) + ")")

When executed, three parameters are output. DIM: Angle of view K: Radial strain coefficient D: Circumferential distortion coefficient

undistort.py


import numpy as np
import cv2
import sys
import os

# You should replace these 3 lines with the output in calibration step
DIM=##
K=##
D=##

def undistort(img_path):
    img = cv2.imread(img_path)
    h,w = img.shape[:2]
    map1, map2 = cv2.fisheye.initUndistortRectifyMap(K, D, np.eye(3), K, DIM, cv2.CV_16SC2)
    undistorted_img = cv2.remap(img, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
    # cv2.imshow("undistorted", undistorted_img)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    cv2.imwrite('out_' + os.path.basename(img_path), undistorted_img)
if __name__ == '__main__':
    for p in sys.argv[1:]:
        undistort(p)

Execution example

Bebop2_20201027162227+0900.jpg

out_Bebop2_20201027162227+0900.jpg

reference

  1. If you detect an object with a fisheye camera, do you have distortion correction? --Qiita

  2. GitHub - opencv/opencv: Open Source Computer Vision Library

  3. Run C ++ OpenCV on mac. --Qiita

  4. Calibrate fisheye lens using OpenCV — part 1 | by Kenneth Jiang | Medium

Recommended Posts

Fisheye lens correction
Try adding fisheye lens distortion to the image