cv2.calibrateCamera
https://docs.opencv.org/4.x/d9/d0c/group__calib3d.html#ga3207604e4b1a1758aa66acb6ed5aa65d
OpenCV: Camera Calibration and 3D Reconstruction
The functions in this section use a so-called pinhole camera model. The view of a scene is obtained by projecting a scene's 3D point \(P_w\) into the image plane using a perspective transformation which forms the corresponding pixel \(p\). Both \(P_w\) and
docs.opencv.org
알려진 3D 패턴(체스보드 등)의 여러 이미지(10개 이상 권장)로부터
- 카메라의 intrinsic parameters(초점거리, 광학중심): $K$ (Camera Matrix)
- Lens Distrotion Coefficients (렌즈 왜곡 계수)를 계산하는 함수.
retval, cameraMatrix, distCoeffs, rvecs, tvecs = cv2.calibrateCamera(
objectPoints,
imagePoints,
imageSize,
cameraMatrix=None,
distCoeffs=None,
rvecs=None,
tvecs=None,
flags=0,
criteria=(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-6)
)
Parameters
objectPoints: 리스트;- 각 요소는
(N, 3)또는(1, N, 3)형태의 NumPy 배열. - 여기서
N은 이미지당 corner (points)의 갯수. - 설명:
- 실제 세계의 3D 점들의 좌표.
- 각 캘리브레이션 이미지에 대한 3D 좌표임.
- 대부분의 경우, z=0으로 설정하여 처리됨 (동일한 평면에 대해 카메라를 이동시켜서 촬영하면서 거리는 유지.)
- 기본값: 없음 (필수 입력)
- 각 요소는
imagePoints: 리스트;- 각 요소는
(N, 2)또는(1, N, 2)형태의 NumPy 배열. - 설명:
- 이미지 평면상의 2D 점들의 좌표.
objectPoints의 3D 점들이 이미지에 투영되어 감지된 좌표들 포함.
- 기본값: 없음 (필수 입력)
- 각 요소는
imageSize: 튜플(width, height)형태.- 설명:
- 캘리브레이션에 사용된 이미지의 크기
- 픽셀 단위.
- 기본값: 없음 (필수 입력)
cameraMatrix(옵션)(3, 3)형태의 NumPy 배열 또는None.- 설명:
- 입력/출력 카메라 매트릭스 (=Intrinsic Matrix).
- argument로 초기 intrinsic parameters를 제공할 때 이용.
- 기본값:
None(함수 내에서 자동으로 초기화)
distCoeffs(옵션)(4, 1),(5, 1),(8, 1),(12, 1)형태의 NumPy 배열 또는None.- 주로 None 또는 (5,1)의 형태를 주로 사용
- 설명:
- 입력/출력 distortion coefficient vector(왜곡 계수 벡터).
- 초기 왜곡 계수를 제공할 때 이용.
- 기본값:
None(함수 내에서 자동으로 초기화)
rvecs(옵션) :** 리스트;- 각 요소는
(3, 1)형태의 NumPy 배열. - 설명:
- 각 캘리브레이션 이미지에 대한 rotation 벡터: Rodriguse Vector
- 기본값:
None(함수에서 자동으로 계산되므로 일반적으로 지정하지 않음)
- 각 요소는
tvecs(옵션) : 리스트;- 각 요소는
(3, 1)형태의 NumPy 배열. - 설명:
- 각 캘리브레이션 이미지에 대한 Translation Vector.
- 기본값:
None(함수에서 자동으로 계산되므로 일반적으로 지정하지 않)
- 각 요소는
flags(옵션) : 정수형.- 설명:
- 캘리브레이션 프로세스를 제어하는 Flags.
- 여러 Flags를 Bitwise OR 연산자
|를 사용하여 결합.
- 기본값:
0(기본 동작) - 주요 플래그:
cv2.CALIB_USE_INTRINSIC_GUESS(1):cameraMatrix에 제공된 초기 값을 사용.cv2.CALIB_FIX_PRINCIPAL_POINT(4): Principal Point를 고정.cv2.CALIB_FIX_ASPECT_RATIO(2): Aspect Ratio를 고정.cv2.CALIB_ZERO_TANGENT_DIST(8): Tanggent Distortion Coef.를 0으로 설정.cv2.CALIB_FIX_K1~cv2.CALIB_FIX_K6: 특정 Distortion Coef.를 고정.cv2.CALIB_RATIONAL_MODEL(16384): rational distortion coef.을 사용.
- 설명:
criteria(옵션) : 튜플(type, maxCount, epsilon)형태.
- 설명:
- 최적화 알고리즘의 종료 조건.
- 알고리즘이 원하는 정확도(
epsilon)에 도달하거나 - 최대 반복 횟수(
maxCount)에 도달하면 종료.
- 기본값:
(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-6)
- 기본 종료 조건 설명:
type:cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER(두 조건 모두 사용)maxCount:30(최대 30번의 반복)epsilon:1e-6(허용 오차)
Return Value
retval: 부동소수점(float).- 전체 RMS Reprojection Error(재투영 오차).
- 캘리브레이션의 품질을 나타내며, 값이 작을수록 좋음.
cameraMatrix:(3, 3)형태의 NumPy 배열.- 계산된 카메라 매트릭스(Intrinsic Parameters).
distCoeffs: NumPy 배열.- Distortion Error Vector.
rvecs: 리스트;- 각 요소는
(3, 1)형태의 NumPy 배열. - 각 캘리브레이션 이미지에 대한 rotation vector.
- 각 요소는
tvecs: 리스트;- 각 요소는
(3, 1)형태의 NumPy 배열. - 각 캘리브레이션 이미지에 대한 Translation Vector.
- 각 요소는
파라미터 상세 설명
1. objectPoints
- 필수 입력이며, 실제 세계에서의 3D 좌표를 제공.
- 일반적으로 체스보드 패턴의 코너 좌표를 사용, 단위는 밀리미터나 센티미터 등 일관되게 사용.
- 각 이미지마다 동일한 패턴의 좌표를 사용.
- 실제로는 리스트의 각 요소가 3D 점들의 배열.
2. imagePoints
- 필수 입력이며, 각 이미지에서 감지된 2D 코너 좌표를 제공.
objectPoints의 3D 점들과 정확히 대응되어야 함 (같은 숫자).
3. imageSize
- 필수 입력이며, 캘리브레이션에 사용된 이미지의 크기를
(width, height)형태의 튜플로 제공. - 이 크기는
imagePoints를 얻을 때 사용된 이미지의 크기와 일치해야 함.
4. cameraMatrix
- 초기 카메라 매트릭스를 제공하고자 할 때 이용.
- 기본값은
None이며, 이 경우 함수 내에서 합리적인 초기 추정값을 자동으로 생성. flags에cv2.CALIB_USE_INTRINSIC_GUESS를 설정하면- 이 parameter로 제공된
cameraMatrix를 초기값으로 사용.
5. distCoeffs
- 초기 distortion coefficient vector를 제공하고자 할 때 사용.
- 기본값은
None이며, 이 경우 함수 내에서 초기값을 0으로 설정. - radial distortion 참고자료: https://dsaint31.tistory.com/614
- tangential distortion 참고자료: https://dsaint31.tistory.com/799
6. rvecs와 tvecs
- 각 이미지에 대한 회전 및 변환 벡터를 저장.
- 기본값은
None이며, 함수 실행 후 결과 값으로 반환.
7. flags
- 캘리브레이션 과정을 제어하는 flags.
- 기본값은
0으로, 이는 특별한 제약 없이 기본 캘리브레이션을 수행함을 의미.
8. criteria
- Optimization 의 종료 조건을 지정.
- 기본값은
(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-6)로 설정됨. - 이 값은 알고리즘이 최대 30번의 반복을 수행하거나, 오차가
1e-6이하로 떨어지면 종료됨을 의미.
예제 코드
import cv2
import numpy as np
import glob
# 코너 세부 조정을 위한 종료 조건 (기본값과 동일)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-6)
# 체스보드 패턴의 내부 코너 수 설정
pattern_size = (7, 6) # x축에 7개, y축에 6개의 내부 코너
# 실제 세계의 3D 점 준비
objp = np.zeros((pattern_size[0]*pattern_size[1], 3), np.float32)
objp[:, :2] = np.mgrid[0:pattern_size[0], 0:pattern_size[1]].T.reshape(-1, 2)
object_points = [] # 3D 점들의 배열
image_points = [] # 2D 점들의 배열
# 캘리브레이션 이미지 불러오기
images = glob.glob('calibration_images/*.jpg')
for fname in images:
img = cv2.imread(fname)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
image_size = gray.shape[::-1]
# 체스보드 코너 찾기
ret, corners = cv2.findChessboardCorners(gray, pattern_size, None)
if ret:
object_points.append(objp)
# 코너 위치 세부 조정
corners2 = cv2.cornerSubPix(gray, corners, (11,11), (-1,-1), criteria)
image_points.append(corners2)
# 코너 그리기 및 표시 (옵션)
cv2.drawChessboardCorners(img, pattern_size, corners2, ret)
cv2.imshow('Calibration Image', img)
cv2.waitKey(100)
cv2.destroyAllWindows()
# 카메라 캘리브레이션 수행 (기본값 사용)
ret, camera_matrix, dist_coeffs, rvecs, tvecs = cv2.calibrateCamera(
object_points,
image_points,
image_size,
cameraMatrix=None,
distCoeffs=None,
flags=0,
criteria=(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-6)
)
# 결과 출력
print("RMS 재투영 오차:", ret)
print("카메라 매트릭스:\n", camera_matrix)
print("왜곡 계수:\n", dist_coeffs)
추가 정보
- Distortion Coefficient Vector의 형태:
- 기본적으로 radial distortion coef.
k1,k2,k3와 - tangetial distortion coef.
p1,p2로 구성된 (k1, k2, p1, p2, k3)를 사용.flags를 통해 다른 형태의 distortion coef. vector를 사용 가능.
- 기본적으로 radial distortion coef.
- 캘리브레이션 품질 평가:
- 반환된
retval값(RMS reprojection error)을 통해 캘리브레이션의 품질을 평가 가능. - 값이 작을수록 캘리브레이션이 정확함을 의미.
- 반환된
- 결과 저장 및 활용:
- 캘리브레이션 결과를 저장하여
- 이후 이미지 왜곡 보정이나 3D Reconstruction에 활용.
image 왜곡보정
undistorted_img = cv2.undistort(img, camera_matrix, dist_coeffs)

Videostream에서의 왜곡보정
h, w = img.shape[:2]
new_camera_matrix, roi = cv2.getOptimalNewCameraMatrix(camera_matrix, dist_coeffs, (w, h), 1, (w, h))
mapx, mapy = cv2.initUndistortRectifyMap(camera_matrix, dist_coeffs, None, new_camera_matrix, (w, h), 5)
undistorted_img = cv2.remap(img, mapx, mapy, cv2.INTER_LINEAR)
같이 보면 좋은 자료들
https://docs.opencv.org/4.x/dc/dbb/tutorial_py_calibration.html
OpenCV: Camera Calibration
Goal In this section, we will learn about types of distortion caused by cameras how to find the intrinsic and extrinsic properties of a camera how to undistort images based off these properties Basics Some pinhole cameras introduce significant distortion t
docs.opencv.org
https://gist.github.com/dsaint31x/5c5dfe8e2a57bd6ffe8560d6a2f3b86b
dip_camera_calibration.ipynb
dip_camera_calibration.ipynb. GitHub Gist: instantly share code, notes, and snippets.
gist.github.com
2025.07.04 - [Python] - cv.undistort()와 cv.initUndistortRectifyMap() + cv.remap()
cv.undistort()와 cv.initUndistortRectifyMap() + cv.remap()
OpenCV는cv.calibrateCamera() 를 통해 얻은camera matrix와 distortion coefficients를 이용하여undistorted image를 생성하는 방법으로다음 2가지를 지원함:cv.undistort()cv.initUndistortRectifyMap() + cv.remap()관련 gist URLhttps://g
ds31x.tistory.com
https://dsaint31.tistory.com/748
[CV] Geometric Camera Model and Camera Calibration: Pinhole Camera
Geometric Camera Model (or Camera Model)은 real world 의 scene 과 camera의 pose (= orientation + location) 에 따라,real world 의 scene 과 camera의 image 간의 기하학적 관계(geometrical relation)를approximation 함.참고: 2D image를 3D s
dsaint31.tistory.com
[CV] Chessboard관련 함수들: OpenCV
cv.findChessboardCorners()cv.findChessboardCorners() 함수는 OpenCV 라이브러리에서 제공하는 함수chessboard 패턴의 코너를 찾는 데 사용됨.이 함수는 camera calibration 과정에서 자주 사용됨.입력 이미지에서 chessbo
ds31x.tistory.com
https://dsaint31.tistory.com/733
[OpenCV] cornerSubPix : 코너 검출 정확도 향상
OpenCV 라이브러리에서 제공하는 cornerSubPix는코너 검출의 정확도를 높이기 위해 사용되는 함수임.이 함수는 초기 검출된 코너 위치를 서브픽셀 수준으로 정밀하게 조정하기 위해 사용됨.함수 설
dsaint31.tistory.com
'Python' 카테고리의 다른 글
| [Py] Debugging: pdb and ipdb (0) | 2024.09.25 |
|---|---|
| [Py] assert 구문 (statement) (1) | 2024.09.24 |
| [Etc] SW Version: Semantic Versioning + packaging.version (0) | 2024.09.19 |
| [Summary] NumPy(Numerical Python) (3) | 2024.09.12 |
| [Py] sys.exit() (1) | 2024.09.11 |