camera calibration과 왜곡 보정 (2)

정예슬·2023년 1월 25일
0

vision

목록 보기
2/21

이전 포스팅에서는 핀홀 카메라를 기준으로 캘리브레이션을 수행했었는데, 화각이 넓은 어안 카메라(fisheye camera)의 경우 조금 다른 방식으로 intrinsic parameter를 구하게 된다.

opencv의 fisheye module에서 어안 카메라의 캘리브레이션 과정을 지원하고 있으며, 이 방식대로 캘리브레이션을 수행해 보겠다.


fisheye camera calibration

fisheye camera에서의 intrinsic parameters는 K와 D가 있다.

캘리브레이션(calibration)

본 캘리브레이션 과정에서도 약 20장 정도의 10 * 15 체커보드 이미지를 촬영하여 사용하였는데, 테두리 부분을 제외하고 CHECKERBOARD = (14, 9) 로 표시한다.

(처음에 15, 10 했다가 안되길래 한참 헤맸다.. 꼭 체크 개수 -1 씩 해줘야 함 !!!😖)

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 = (14,9)
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('./cali_images/*.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 ret == True:
        objpoints.append(objp)
        cv2.cornerSubPix(gray,corners,(3,3),(-1,-1),subpix_criteria)
        imgpoints.append(corners)
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()) + ")")

왜곡 보정(undistort)

def undistort(image, balance=0.0, dim2=None, dim3=None):
    dim1 = image.shape[:2][::-1] 
    assert dim1[0]/dim1[1] == DIM[0]/DIM[1], 
    if not dim2:
        dim2 = dim1
    if not dim3:
        dim3 = dim1
    scaled_K = K * dim1[0] / DIM[0] 
    scaled_K[2][2] = 1.0 
    new_K = cv2.fisheye.estimateNewCameraMatrixForUndistortRectify(scaled_K, 
   									 D,dim2, np.eye(3), balance=balance)
    map1, map2 = cv2.fisheye.initUndistortRectifyMap(scaled_K, D, 
    									np.eye(3), new_K,dim3, cv2.CV_16SC2)
    undistorted_img = cv2.remap(image, map1, map2,
    				interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
                    
    cv2.imshow("undistorted", undistorted_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

calibration에서 검출된 파라미터들을 위에서 정의한 후, undistort 함수를 사용하면 왜곡이 보정된 이미지를 획득할 수 있다. 내가 테스트한 카메라의 파라미터는 다음과 같이 나왔다.


DIM=(1920, 1080)
K=np.array([[1041.721033566984, 0.0, 982.4318615455983], [0.0, 1041.0260709694585, 431.8071863472761], [0.0, 0.0, 1.0]])
D=np.array([[-0.07960228346280786], [0.4447533452768294], [-1.6226455570763598], [1.907617662076584]])

왼쪽이 보정 전, 보정 후의 이미지인데 노란 선 부분과 검은색 판의 곡선 부분이 많이 개선된 것을 볼 수 있다.

profile
춘식이랑 함께하는 개발일지

1개의 댓글

comment-user-thumbnail
2023년 3월 3일

안녕 하세요 체커 보드 한변의 길이는 어디서 수정 하나요?? mm 참고하신 원문에서 제공하는 a4 사이즈 체커 보드가 다운로드 불가능하네요

답글 달기