Skip to content

OpenCV 치트시트

오픈소스 컴퓨터 비전 및 머신러닝 라이브러리입니다.

01

시작하기

이미지 읽기, 표시, 저장

OpenCV는 (RGB가 아니라) BGR 순서로 이미지를 읽습니다. matplotlib이나 PIL과 상호운용할 때 흔한 함정입니다. cv2.waitKey(0)는 키 입력까지 블로킹되며 창을 닫으려면 항상 destroyAllWindows()를 호출하세요. JPEG 품질은 0~100입니다.

opencv
import cv2
import numpy as np

# read an image (BGR format by default)
img = cv2.imread("photo.jpg")
print(img.shape)  # (height, width, channels)

# read as grayscale
gray = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

# read with alpha channel
rgba = cv2.imread("logo.png", cv2.IMREAD_UNCHANGED)

# display
cv2.imshow("window", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save
cv2.imwrite("output.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 90])

설치와 임포트

opencv-python은 메인 모듈만 제공하고, opencv-contrib-python은 SIFT/SURF, ArUco 같은 추가(종종 특허 걸린) 모듈을 더합니다. 서버/Docker에서는 X11 의존성을 끌지 않도록 headless 변형을 쓰세요. 이름이 cv2인데도 OpenCV 4.x는 여전히 cv2로 임포트합니다.

opencv
# Install OpenCV (Python bindings)
pip install opencv-python          # main modules only
pip install opencv-contrib-python  # includes extra modules (SIFT, SURF, aruco...)
pip install opencv-python-headless # no GUI (servers / Docker)

# The universal alias is cv2
import cv2
print(cv2.__version__)             # e.g. 4.9.0

# NumPy is required — images are ndarray
import numpy as np

NumPy 배열로서의 이미지

OpenCV 이미지는 NumPy 배열이므로 NumPy에 관한 모든 지식이 적용됩니다. 좌표 관례는 img[y, x](행, 열)이며 (x, y) 이미지 좌표와 반대입니다. 잦은 버그의 원천입니다. 컬러 이미지는 (H, W, 3) BGR이고, 그레이스케일은 (H, W)입니다.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")   # BGR uint8, shape (H, W, 3)
print(type(img))                # <class 'numpy.ndarray'>
print(img.shape, img.dtype)     # (480, 640, 3) uint8

# A grayscale image is 2-D: (H, W)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(gray.shape)               # (480, 640)

# Coordinate convention: img[y, x]  (row, col)
px = img[100, 200]              # BGR pixel at (x=200, y=100)
blue, green, red = img[100, 200]

# Vectorized access to a region (ROI)
roi = img[50:150, 100:300]      # rows 50-149, cols 100-299

픽셀 접근과 ROI

img[y, x]의 픽셀별 접근은 느리고 루프에서는 권장되지 않습니다. 항상 NumPy 슬라이싱을 선호하세요. ROI를 할당할 때 .copy()를 쓰면 이후 원본 변경이 스며들지 않습니다. img[:, :, channel] 수정이 단일 색상 채널을 다루는 가장 빠른 방법입니다.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")

# access a single pixel (slow)
b, g, r = img[100, 200]

# access a single channel faster
blue = img[100, 200, 0]
img[100, 200] = [255, 255, 255]   # set to white

# numpy slicing is much faster than item-by-item
roi = img[100:200, 200:400].copy()

# copy ROI to another location
img[0:100, 0:200] = roi

# modify a whole channel
img[:, :, 2] = 0   # zero out the red channel

데이터 타입과 변환

대부분의 OpenCV 함수는 uint8(0-255)을 기대하지만 SIFT, 광학 흐름, 엣지 검출 같은 알고리즘은 종종 float32가 필요합니다. 뺄셈 후 .astype()으로 바로 캐스트하지 마세요. uint8 오버플로가 -1을 255로 만듭니다. cv2.absdiff를 쓰거나 먼저 float으로 변환하세요. cv2.imwrite / imshow 전에는 항상 uint8로 되돌리세요.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")      # uint8, 0-255
print(img.dtype, img.min(), img.max())   # uint8 0 255

# convert to float32 (0.0-1.0 for many algorithms)
f = img.astype(np.float32) / 255.0

# convert back to uint8 for display/save
u = (f * 255).astype(np.uint8)

# clamp then cast (avoid overflow when subtracting)
diff = cv2.absdiff(img, img)       # safe subtraction
print(diff.dtype)                  # uint8

# CV_32F / CV_64F / CV_8U constants (used in some functions)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(gray.dtype)                  # uint8
02

비디오 캡처

웹캠 열기

VideoCapture(0)가 기본 웹캠을 열며 추가 카메라는 1, 2...를 씁니다. 장치를 해제하려 항상 cap.release()를 호출하세요. 잊으면 카메라가 다른 앱에 점유될 수 있습니다. waitKey(1)는 약 1ms 기다리고, & 0xFF 트릭은 waitKey가 8비트 이상을 반환하는 64비트 시스템에서의 호환성을 보장합니다.

opencv
import cv2

cap = cv2.VideoCapture(0)           # 0 = default camera
print(cap.isOpened())              # True if camera opened

while True:
    ret, frame = cap.read()        # ret is False at end of stream
    if not ret:
        break

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow("frame", gray)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

비디오 파일 읽기

CAP_PROP_FRAME_COUNT는 종종 근사이며 일부 코덱에서 불신뢰합니다. 정확한 시킹에는 의존하지 마세요. waitKey(int(1000/fps))가 대략 올바른 속도로 재생하며 정밀한 타이밍에는 실제 시계를 쓰세요. 일부 압축 비디오는 올바른 백엔드(FFmpeg)가 없으면 열리지 않습니다.

opencv
import cv2

cap = cv2.VideoCapture("movie.mp4")

# video properties
fps    = cap.get(cv2.CAP_PROP_FPS)
width  = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
count  = cap.get(cv2.CAP_PROP_FRAME_COUNT)
print(f"{width}x{height} @ {fps} fps, {count} frames")

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    cv2.imshow("video", frame)
    if cv2.waitKey(int(1000 / fps)) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

비디오 저장 / 쓰기

FourCC 코드는 플랫폼과 코덱에 따라 다릅니다. 'mp4v'가 널리 이식 가능하고, 'XVID'는 .avi를, 'avc1'은 H.264를 만듭니다(독점 코덱이 없으면 불가할 수 있음). VideoWriter에 전달하는 프레임 크기는 쓰는 프레임과 반드시 일치해야 하며 아니면 파일이 손상됩니다. 플러시와 파일 닫기를 위해 항상 out.release()를 호출하세요.

opencv
import cv2

cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')   # or 'XVID', 'avc1'
fps = 20.0
size = (640, 480)
out = cv2.VideoWriter("out.mp4", fourcc, fps, size)

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    frame = cv2.resize(frame, size)
    out.write(frame)
    cv2.imshow("rec", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

카메라 설정

카메라 속성은 하드웨어와 드라이버에 따라 다릅니다. 많은 웹캠이 지원되지 않는 설정을 조용히 무시하거나 가장 가까운 유효 값에 붙으므로 항상 실제 값을 다시 읽으세요. CAP_PROP_EXPOSURE는 초의 log2입니다(-4 = 1/16초). 대부분의 카메라에서 수동 노출이 적용되려면 자동 노출을 먼저 비활성화(1로 설정)해야 합니다.

opencv
import cv2

cap = cv2.VideoCapture(0)

# set resolution
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)

# set exposure / focus / brightness
cap.set(cv2.CAP_PROP_EXPOSURE, -4)      # log2 exposure time
cap.set(cv2.CAP_PROP_BRIGHTNESS, 128)
cap.set(cv2.CAP_PROP_AUTO_EXPOSURE, 1)  # 1=manual, 3=auto

# disable autofocus and set manual focus
cap.set(cv2.CAP_PROP_AUTOFOCUS, 0)
cap.set(cv2.CAP_PROP_FOCUS, 50)

print(cap.get(cv2.CAP_PROP_FRAME_WIDTH))   # actual width may differ

프레임 레이트와 타이밍

cap.get(CAP_PROP_FPS)는 설정된 FPS이지 실제 캡처 비율이 아니므로 실제 시계로 측정하세요. 30프레임 이동 평균이 지터를 부드럽게 합니다. 가장 큰 FPS 킬러는 cv2.imshow(GUI 스레드)와 프레임별 cv2.imwrite이며, 벤치마크에서는 표시를 끄세요. 결정적 타이밍을 위해 스레드에서 프레임을 쌓고 큐에서 처리하세요.

opencv
import cv2
import time

cap = cv2.VideoCapture(0)
prev = time.time()
fps_hist = []

while True:
    ret, frame = cap.read()
    if not ret:
        break

    now = time.time()
    dt = now - prev
    prev = now
    if dt > 0:
        fps_hist.append(1.0 / dt)
        fps = sum(fps_hist[-30:]) / min(len(fps_hist), 30)
        cv2.putText(frame, f"FPS: {fps:.1f}", (10, 30),
                    cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

    cv2.imshow("fps", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
03

그리기

선과 사각형

모든 그리기 함수는 이미지를 제자리 수정하므로 원본을 유지하려 복사본을 전달하세요. 좌표는 (x, y)로 NumPy의 [y, x] 인덱싱과 반대입니다. 색은 BGR 튜플입니다. 채워진 도형에는 thickness=-1, 대각선 모서리의 부드러운(안티앨리어싱) 선에는 cv2.LINE_AA를 쓰세요.

opencv
import cv2
import numpy as np

img = np.zeros((400, 400, 3), dtype=np.uint8)

# line(img, pt1, pt2, color, thickness)
cv2.line(img, (10, 10), (390, 10), (0, 255, 0), 2)

# rectangle(img, pt1, pt2, color, thickness)
cv2.rectangle(img, (50, 50), (200, 150), (255, 0, 0), 3)

# filled rectangle (thickness = -1)
cv2.rectangle(img, (220, 50), (370, 150), (0, 0, 255), -1)

# anti-aliased line (cv2.LINE_AA)
cv2.line(img, (10, 380), (390, 200), (255, 255, 0), 1, cv2.LINE_AA)

cv2.imshow("img", img)
cv2.waitKey(0)

원과 타원

ellipse의 axes 파라미터는 (halfWidth, halfHeight)이며 전체 폭은 2 * axes[0]입니다. angle이 전체 타원을 회전하고, startAngle/endAngle이 부분 호를 그립니다(0° = 오른쪽, 반시계 방향). 부분 호 그리기가 파이 차트 조각이나 움직임 방향 표시기의 표준 방법입니다.

opencv
import cv2
import numpy as np

img = np.zeros((400, 400, 3), dtype=np.uint8)

# circle(img, center, radius, color, thickness)
cv2.circle(img, (100, 100), 50, (0, 255, 255), 3)
cv2.circle(img, (300, 100), 50, (255, 0, 255), -1)   # filled

# ellipse(img, center, axes, angle, startAngle, endAngle, color, thickness)
cv2.ellipse(img, (200, 250), (100, 50), 30, 0, 360, (0, 255, 0), 2)

# partial arc (0 to 180 degrees)
cv2.ellipse(img, (200, 250), (100, 50), 30, 0, 180, (0, 0, 255), 3)

cv2.imshow("img", img)
cv2.waitKey(0)

다각형과 폴리라인

polylines는 점 배열의 리스트를 받으므로 한 번의 호출로 여러 다각형을 그릴 수 있습니다. 점 배열은 int32이고 (-1, 1, 2)로 reshape해야 합니다. 채워진 도형에는 fillPoly를 쓰고, 반투명 채우기는 오버레이에 그린 뒤 addWeighted로 블렌딩하세요. isClosed 플래그가 마지막 점을 첫 점과 연결합니다.

opencv
import cv2
import numpy as np

img = np.zeros((400, 400, 3), dtype=np.uint8)

# polygon points: shape (N, 1, 2), int32
pts = np.array([[50, 50], [200, 30], [350, 200],
                [300, 350], [80, 300]], dtype=np.int32)
pts = pts.reshape((-1, 1, 2))

# outline only (not closed)
cv2.polylines(img, [pts], False, (0, 255, 0), 2)

# closed polygon outline
cv2.polylines(img, [pts], True, (255, 0, 0), 3)

# filled polygon
cv2.fillPoly(img, [pts], (0, 0, 255))

cv2.imshow("img", img)
cv2.waitKey(0)

텍스트

OpenCV 내장 폰트는 Hershey 벡터 폰트로 CJK/중국어 문자를 지원하지 않습니다. 비라틴 텍스트는 PIL(Pillow) ImageFont로 렌더링해 되돌리거나 opencv-contrib의 cv2.freetype을 쓰세요. getTextSize는 ((width, height), baseline)을 반환해 텍스트 중앙 정렬이나 배경 박스 그리기에 유용합니다.

opencv
import cv2
import numpy as np

img = np.zeros((300, 600, 3), dtype=np.uint8)

# putText(img, text, org, fontFace, fontScale, color, thickness)
cv2.putText(img, "Hello OpenCV", (10, 50),
            cv2.FONT_HERSHEY_SIMPLEX, 1.2, (255, 255, 255), 2)

# fonts
fonts = [cv2.FONT_HERSHEY_SIMPLEX, cv2.FONT_HERSHEY_PLAIN,
         cv2.FONT_HERSHEY_DUPLEX, cv2.FONT_HERSHEY_COMPLEX,
         cv2.FONT_HERSHEY_TRIPLEX, cv2.FONT_ITALIC]
for i, f in enumerate(fonts):
    cv2.putText(img, f"font {i}", (10, 100 + i*30), f, 0.8, (0, 255, 0), 1)

# measure text size before drawing
(text_w, text_h), baseline = cv2.getTextSize(
    "Measured", cv2.FONT_HERSHEY_SIMPLEX, 1.0, 2)
cv2.rectangle(img, (10, 260), (10 + text_w, 260 + text_h + baseline),
              (0, 0, 255), 1)

화살표와 마커

arrowedLine의 tipLength는 선 길이의 비율이므로 긴 화살표일수록 끝이 비례적으로 커집니다. 일관된 화살촉 크기를 원하면 명시적으로 설정하세요. drawMarker는 핵심 지점(예: 검출된 피처나 코너) 강조에 편리하며, MARKER_TILTED_CROSS가 X자 마커를 줍니다.

opencv
import cv2
import numpy as np

img = np.zeros((400, 400, 3), dtype=np.uint8)

# arrowedLine(img, pt1, pt2, color, thickness, tipLength)
cv2.arrowedLine(img, (50, 50), (350, 50), (0, 255, 0), 2, tipLength=0.05)
cv2.arrowedLine(img, (200, 200), (200, 380), (0, 0, 255), 3, tipLength=0.1)

# drawMarker (cross, tilted cross, circle, square, diamond)
cv2.drawMarker(img, (100, 300), (255, 0, 255),
               markerType=cv2.MARKER_CROSS, markerSize=30, thickness=2)
cv2.drawMarker(img, (300, 300), (255, 255, 0),
               markerType=cv2.MARKER_DIAMOND, markerSize=30, thickness=2)

cv2.imshow("img", img)
cv2.waitKey(0)

오버레이와 주석

오버레이 기법(복사본에 그린 뒤 addWeighted)이 반투명 채우기의 표준 방법입니다. OpenCV에는 도형용 네이티브 알파가 없습니다. 선명하게 유지하려 블렌딩 '후에' 단색 텍스트를 그리세요. 블렌딩 전 오버레이에 텍스트를 그리면 흐려집니다. 이 패턴은 검출/세그먼테이션 시각화 어디에나 있습니다.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")
overlay = img.copy()

# draw a translucent rectangle on the overlay
cv2.rectangle(overlay, (50, 50), (250, 150), (0, 0, 255), -1)
cv2.putText(overlay, "REGION", (60, 110),
            cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)

# blend overlay onto the original (alpha=0.4)
out = cv2.addWeighted(overlay, 0.4, img, 0.6, 0)

cv2.imshow("out", out)
cv2.waitKey(0)
04

이미지 산술

Add와 Subtract

OpenCV의 cv2.add는 255에서 포화되지만(250 + 10 = 255) NumPy의 +는 wrap합니다(uint8 오버플로로 250 + 10 = 8). 이미지에는 항상 cv2.add / cv2.subtract를 쓰세요. wrap은 눈에 보이는 검정/흰색 아티팩트를 만듭니다. absdiff가 배경 차분과 움직임 검출의 주력입니다.

opencv
import cv2
import numpy as np

a = cv2.imread("a.jpg")
b = cv2.imread("b.jpg")
b = cv2.resize(b, (a.shape[1], a.shape[0]))   # match sizes

# OpenCV addition: saturated (caps at 255)
add_cv = cv2.add(a, b)

# NumPy addition: wraps around (250 + 10 = 264 -> 8)
add_np = a + b

# subtract (saturated, never goes below 0)
sub = cv2.subtract(a, b)

# absolute difference (handy for motion detection)
diff = cv2.absdiff(a, b)

블렌딩과 AddWeighted

addWeighted는 두 이미지의 크기와 dtype이 동일해야 하므로 먼저 resize하세요. gamma 항이 모든 픽셀에 상수를 더해 밝기 조절에 유용합니다. 두 이미지 간 고전적 페이드/크로스 디졸브는 alpha를 0에서 1로 훑는 addWeighted일 뿐입니다.

opencv
import cv2
import numpy as np

a = cv2.imread("a.jpg")
b = cv2.imread("b.jpg")
b = cv2.resize(b, (a.shape[1], a.shape[0]))

# dst = alpha * a + beta * b + gamma
blend = cv2.addWeighted(a, 0.7, b, 0.3, 0)

# brighten by adding a constant (gamma)
bright = cv2.addWeighted(a, 1.0, a, 0.0, 50)

# fade between two images over N steps
for i in range(11):
    alpha = i / 10.0
    frame = cv2.addWeighted(a, alpha, b, 1 - alpha, 0)
    cv2.imshow("fade", frame)
    cv2.waitKey(200)

Bitwise 연산

bitwise 연산이 마스크 적용의 표준 방법입니다. cv2.bitwise_or(src, dst, mask=mask)는 마스크가 0이 아닌 곳에만 src를 dst로 복사합니다. 마스크는 0이 아니면 '유지'를 뜻하는 단일 채널 8비트 이미지여야 합니다. ROI 추출과 배경 교체의 기초입니다.

opencv
import cv2
import numpy as np

a = np.zeros((200, 200), dtype=np.uint8)
cv2.rectangle(a, (20, 20), (120, 120), 255, -1)

b = np.zeros((200, 200), dtype=np.uint8)
cv2.circle(b, (100, 100), 60, 255, -1)

# bitwise AND / OR / XOR / NOT
and_ = cv2.bitwise_and(a, b)
or_  = cv2.bitwise_or(a, b)
xor  = cv2.bitwise_xor(a, b)
not_ = cv2.bitwise_not(a)

# use a mask to copy only part of an image
mask = np.zeros((200, 200), dtype=np.uint8)
cv2.circle(mask, (100, 100), 50, 255, -1)
src = np.full((200, 200, 3), (0, 255, 0), dtype=np.uint8)
dst = cv2.imread("photo.jpg")
dst = cv2.resize(dst, (200, 200))
result = cv2.bitwise_or(src, dst, mask=mask)

이미지 차분과 움직임

프레임 차분이 가장 단순한 움직임 검출기입니다. 연속 프레임의 절대 차이에 임계값을 적용합니다. 카메라가 움직이면 실패하고 느린 움직임을 무시하므로 실제 시스템은 배경 차분(cv2.createBackgroundSubtractorMOG2)이나 광학 흐름을 쓰세요. 형태학적 opening이 노이즈를 제거하고 dilation이 인접 블롭을 합칩니다.

opencv
import cv2
import numpy as np

prev = cv2.imread("frame1.jpg", cv2.IMREAD_GRAYSCALE)
curr = cv2.imread("frame2.jpg", cv2.IMREAD_GRAYSCALE)

# absolute difference
diff = cv2.absdiff(prev, curr)

# threshold to get a binary motion mask
_, mask = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)

# clean up with morphology
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
mask = cv2.dilate(mask, kernel, iterations=2)

# find moving contours
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    if cv2.contourArea(c) > 500:
        x, y, w, h = cv2.boundingRect(c)
        cv2.rectangle(curr, (x, y), (x+w, y+h), (0, 255, 0), 2)

ROI와 마스킹

마스크를 준 bitwise_and가 불규칙 영역 추출의 관용적 방법입니다. 불리언 NumPy 인덱싱(img[mask])이 더 유연하지만 형상이 있는 이미지가 아니라 플랫 배열을 반환합니다. 재사용할 ROI는 항상 .copy()하세요. 슬라이싱은 원본을 별칭하는 뷰를 반환합니다.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")
h, w = img.shape[:2]

# build a mask: white circle on black background
mask = np.zeros((h, w), dtype=np.uint8)
cv2.circle(mask, (w // 2, h // 2), 150, 255, -1)

# keep only the masked region, zero elsewhere
masked = cv2.bitwise_and(img, img, mask=mask)

# extract ROI by bounding box
roi = img[100:300, 200:500].copy()

# put ROI back (or to a different location)
img[0:200, 0:300] = roi

# boolean mask (NumPy) — also works, but converts to 0/255
bool_mask = np.zeros((h, w), dtype=bool)
bool_mask[100:300, 200:500] = True
img_masked = img.copy()
img_masked[~bool_mask] = 0

포화 vs Wrap

uint8 오버플로 함정: NumPy는 wrap하고(300 -> 44) OpenCV는 포화합니다(300 -> 255). 0-255를 넘을 수 있는 산술에는 cv2.add/subtract를 쓰거나 먼저 int16/float32로 승격했다가 다시 클립하세요. 같은 파이프라인에서 cv2와 NumPy 연산을 섞는 것이 신비로운 어두움/밝은 픽셀 아티팩트의 1위 원인입니다.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")

# WRONG: NumPy arithmetic wraps around (200 + 100 -> 44)
bad = img + 100

# RIGHT: cv2.add saturates at 255 (200 + 100 -> 255)
good = cv2.add(img, np.full_like(img, 100))

# subtracting a bright image: cv2 clamps to 0
dark = cv2.subtract(img, np.full_like(img, 100))

# manual saturation (equivalent to cv2.add)
manual = np.clip(img.astype(np.int16) + 100, 0, 255).astype(np.uint8)

# mixing cv2 and numpy is a common bug source:
# half = img // 2          # NumPy: fine (no overflow)
# half_then_add = half + half   # might equal original (ok)
# but bright = img + img  # wraps! 150+150=300 -> 44
05

기하 변환

Resize / 스케일

축소에는 INTER_AREA(앨리어싱 회피)가 최선이고 확대에는 INTER_CUBIC 또는 INTER_LINEAR입니다. INTER_NEAREST가 가장 빠르지만 블록이며, 새 픽셀 값을 도입하면 안 되는 레이블/마스크 이미지에 쓰입니다. dsize 튜플은 (width, height)로 (height, width)인 img.shape과 반대입니다.

opencv
import cv2

img = cv2.imread("photo.jpg")
h, w = img.shape[:2]

# resize to a fixed size
small = cv2.resize(img, (320, 240))

# resize by a scale factor (fx, fy)
big = cv2.resize(img, None, fx=2.0, fy=2.0)

# resize keeping aspect ratio
scale = 0.5
new = cv2.resize(img, (int(w * scale), int(h * scale)))

# interpolation methods
down = cv2.resize(img, (w // 2, h // 2),
                  interpolation=cv2.INTER_AREA)      # shrinking
up   = cv2.resize(img, (w * 2, h * 2),
                  interpolation=cv2.INTER_CUBIC)     # enlarging

회전

90° 배수에는 cv2.rotate가 warpAffine보다 훨씬 빠릅니다. getRotationMatrix2D의 angle은 도 단위이며 양수 = 반시계 방향입니다. 잘림 없이 회전하려 경계 박스(new_w, new_h)를 다시 계산하고 회전 행렬을 이동시키세요. 그렇지 않으면 회전된 큰 이미지의 모서리가 잘립니다.

opencv
import cv2

img = cv2.imread("photo.jpg")
h, w = img.shape[:2]

# rotate 90/180/270 (fast, no interpolation)
rot90  = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
rot180 = cv2.rotate(img, cv2.ROTATE_180)
rot270 = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)

# arbitrary-angle rotation
center = (w // 2, h // 2)
angle = 45
scale = 1.0
M = cv2.getRotationMatrix2D(center, angle, scale)
rot = cv2.warpAffine(img, M, (w, h))

# rotate and expand the canvas to fit the whole image
cos = abs(M[0, 0]); sin = abs(M[0, 1])
new_w = int(h * sin + w * cos)
new_h = int(h * cos + w * sin)
M[0, 2] += (new_w - w) / 2
M[1, 2] += (new_h - h) / 2
rot_fit = cv2.warpAffine(img, M, (new_w, new_h))

아핀 변환

아핀 변환은 평행성과 거리 비율을 보존하며 3개의 점 대응으로 정의됩니다(자유도 6). warpAffine은 역 조회를 통해 전방 매핑을 암묵적으로 쓰므로, M은 src->dst를 매핑하지만 함수가 내부에서 반전합니다. 범위 밖 영역의 채움은 borderMode=BORDER_REFLECT 또는 BORDER_CONSTANT로 제어하세요.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")
h, w = img.shape[:2]

# affine: parallel lines stay parallel (6 DOF)
src = np.float32([[50, 50], [200, 50], [50, 200]])
dst = np.float32([[10, 100], [200, 50], [100, 250]])
M = cv2.getAffineTransform(src, dst)
warped = cv2.warpAffine(img, M, (w, h))

# inverse mapping (destination -> source)
inv = cv2.invertAffineTransform(M)

# translation is a special affine
T = np.float32([[1, 0, 100], [0, 1, 50]])  # shift right 100, down 50
shifted = cv2.warpAffine(img, T, (w, h))

# black border is default; use borderMode for other fill
reflected = cv2.warpAffine(img, T, (w, h),
                           borderMode=cv2.BORDER_REFLECT)

원근 변환

원근(호모그래피)은 일직선 위에 있지 않은 4개 점 쌍으로 정의됩니다(자유도 8). 표준 '문서 스캐너' 변환입니다. 사진에서 카드/종이의 4모서리를 골라 사각형으로 warp합니다. getPerspectiveTransform은 정확히 4점이 필요하며, 과결정 피팅에는 RANSAC과 함께 cv2.findHomography를 쓰세요.

opencv
import cv2
import numpy as np

img = cv2.imread("card.jpg")
h, w = img.shape[:2]

# 4 point correspondences define a perspective (homography)
src = np.float32([[73, 110], [320, 78], [380, 350], [40, 320]])
dst = np.float32([[0, 0], [w, 0], [w, h], [0, h]])

M = cv2.getPerspectiveTransform(src, dst)
warped = cv2.warpPerspective(img, M, (w, h))

# invert the homography to map back
M_inv = cv2.getPerspectiveTransform(dst, src)
restored = cv2.warpPerspective(warped, M_inv, (w, h))

Flip과 Mirror

flip은 저렴한 메모리 연산으로 warpAffine보다 훨씬 빠릅니다. flipCode 부호 관례: 양수는 수평, 0은 수직, 음수는 둘 다입니다. cv2.transpose는 축을 바꾸며 flip과 결합하면 때때로 빠른 90° 회전으로 쓰입니다.

opencv
import cv2

img = cv2.imread("photo.jpg")

# flip(img, flipCode)
#   0  -> vertical flip (around x-axis)  (upside-down)
#   1  -> horizontal flip (around y-axis) (mirror)
#  -1  -> both (180° rotation equivalent)
v = cv2.flip(img, 0)
h = cv2.flip(img, 1)
both = cv2.flip(img, -1)

# transpose (swap x and y axes) — like a 90° rotation + flip
t = cv2.transpose(img)

Remap (커스텀 매핑)

remap이 가장 일반적인 기하 변환입니다. resize, 회전, 심지어 배럴/렌즈 왜곡 보정까지 모두 remap으로 표현됩니다. 맵은 Python 루프가 아니라 NumPy 벡터화로 만드세요(위의 루프 버전은 설명용이며 약 100배 느림). 기본은 INTER_LINEAR이고 모서리의 서브픽셀 정확도에는 INTER_CUBIC을 쓰세요.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")
h, w = img.shape[:2]

# build coordinate maps: map_x, map_y say where each output pixel comes from
map_x = np.zeros((h, w), dtype=np.float32)
map_y = np.zeros((h, w), dtype=np.float32)

for y in range(h):
    for x in range(w):
        # mirror the image
        map_x[y, x] = w - 1 - x
        map_y[y, x] = y

remapped = cv2.remap(img, map_x, map_y, cv2.INTER_LINEAR)

# vectorized version (much faster) — wave distortion
xs, ys = np.meshgrid(np.arange(w), np.arange(h))
map_x = xs.astype(np.float32) + 10 * np.sin(ys / 20.0)
map_y = ys.astype(np.float32) + 10 * np.cos(xs / 20.0)
wave = cv2.remap(img, map_x, map_y, cv2.INTER_LINEAR,
                 borderMode=cv2.BORDER_REFLECT)
06

이미지 필터링

평균 블러 (박스 필터)

평균 블러가 가장 단순한 로우패스 필터입니다. 각 픽셀을 이웃의 평균으로 교체합니다. 커널은 홀수이고 양수여야 합니다. 커널이 클수록 더 흐려지지만 디테일도 더 빨리 파괴됩니다. 균일 가중치를 원할 때 쓰고, 자연 이미지에는 거의 항상 가우시안 블러가 더 낫습니다.

opencv
import cv2

img = cv2.imread("photo.jpg")

# 3x3 box blur
blur3 = cv2.blur(img, (3, 3))

# larger kernel = more blur
blur9 = cv2.blur(img, (9, 9))

# boxFilter with normalized=False gives the sum (not average)
sum_ = cv2.boxFilter(img, -1, (5, 5), normalize=False)

# normalized=True is equivalent to cv2.blur
avg = cv2.boxFilter(img, -1, (5, 5), normalize=True)

가우시안 블러

가우시안 블러가 기본 스무딩 커널입니다. 가우시안으로 이웃을 가중해 박스 필터보다 모서리를 더 잘 보존합니다. ksize=(0,0)과 sigmaX를 전달하면 OpenCV가 커널 크기를 자동 계산합니다. 가우시안 블러는 노이즈 증폭을 억제하려 Canny, 다운샘플링, 라플라시안 전에 필수 선행 단계입니다.

opencv
import cv2

img = cv2.imread("photo.jpg")

# GaussianBlur(img, ksize, sigmaX)
g = cv2.GaussianBlur(img, (5, 5), 0)

# specifying sigma explicitly
g2 = cv2.GaussianBlur(img, (5, 5), sigmaX=1.5, sigmaY=1.5)

# odd kernel size required; (0, 0) auto-derives sigma from ksize
g3 = cv2.GaussianBlur(img, (0, 0), sigmaX=2.0)

# Gaussian is the standard pre-processing step before edge detection
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 50, 150)

중간값 블러

중간값 블러가 소금-후추(임펄스) 노이즈의 기본 필터입니다. 각 픽셀을 이웃의 중앙값으로 교체하므로 고립된 이상값이 퍼지지 않고 제거됩니다. 가우시안과 달리 모서리를 잘 보존합니다. 커널 크기는 홀수여야 합니다. 정렬이 관련되므로 가우시안/박스보다 느립니다.

opencv
import cv2

img = cv2.imread("noisy.jpg")

# median blur — great for salt-and-pepper noise
m = cv2.medianBlur(img, 5)

# larger kernel removes more noise but blurs edges
m2 = cv2.medianBlur(img, 7)

# compared to Gaussian on the same image
g = cv2.GaussianBlur(img, (5, 5), 0)

바이래털 필터

바이래털 필터링은 선명한 모서리를 유지하며 평탄한 영역을 부드럽게 합니다. 공간 근접성과 색 유사성 '둘 다'로 이웃을 가중하는 비선형, 엣지 보존 필터입니다. 가우시안보다 훨씬 느립니다(보통 10배). 반복 적용이 고전적 '만화화' 전처리 단계이며, 큰 sigmaColor가 더 많은 색을 섞습니다.

opencv
import cv2

img = cv2.imread("photo.jpg")

# bilateralFilter(img, d, sigmaColor, sigmaSpace)
#   d            = neighborhood diameter
#   sigmaColor   = how much colors can differ and still blend
#   sigmaSpace   = how far pixels influence each other (spatial)
b = cv2.bilateralFilter(img, d=9, sigmaColor=75, sigmaSpace=75)

# strong edge-preserving smoothing (cartoon effect)
b_strong = cv2.bilateralFilter(img, d=15, sigmaColor=150, sigmaSpace=150)

# repeat several times for a "cartoon / oil painting" look
cartoon = img.copy()
for _ in range(7):
    cartoon = cv2.bilateralFilter(cartoon, d=9, sigmaColor=75, sigmaSpace=75)

샤프닝 (커널)

샤프닝 커널은 고주파를 강조하지만 노이즈도 증폭하므로 노이즈 제거 '후에' 적용하세요. 고전 3x3 샤프닝 커널의 합은 1입니다(밝기 보존). 합이 1을 넘으면 밝아집니다. 언샵 마스크 기법(흐린 복사본 빼기)이 더 제어 가능하며 대부분의 사진 편집기가 실제로 쓰는 방식입니다.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")

# sharpening kernel: center boosts, neighbors subtracted
kernel = np.array([[ 0, -1,  0],
                   [-1,  5, -1],
                   [ 0, -1,  0]], dtype=np.float32)

sharp = cv2.filter2D(img, -1, kernel)

# stronger sharpening
kernel_strong = np.array([[-1, -1, -1],
                          [-1,  9, -1],
                          [-1, -1, -1]], dtype=np.float32)
sharp2 = cv2.filter2D(img, -1, kernel_strong)

# unsharp mask: image + (image - blurred) * amount
blur = cv2.GaussianBlur(img, (0, 0), 3)
unsharp = cv2.addWeighted(img, 1.5, blur, -0.5, 0)

커스텀 커널 (filter2D)

filter2D는 임의 상관 커널을 적용하며 ddepth=-1이 소스 깊이를 유지합니다. 커널은 음수 계수를 위해 float일 수 있습니다. 결과가 음수가 되면 ddepth=cv2.CV_16S 또는 CV_32F로 바꾼 뒤 convertScaleAbs로 되돌리세요. 분리 가능한 커널(1D 커널의 외적)은 sepFilter2D로 훨씬 빠릅니다.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")

# emboss kernel
emboss = np.array([[-2, -1,  0],
                   [-1,  1,  1],
                   [ 0,  1,  2]], dtype=np.float32)
out = cv2.filter2D(img, -1, emboss)

# edge enhance (Laplacian-like)
edge = np.array([[ 0,  1,  0],
                 [ 1, -4,  1],
                 [ 0,  1,  0]], dtype=np.float32)
edges = cv2.filter2D(img, -1, edge)

# box blur done manually
box = np.ones((5, 5), dtype=np.float32) / 25.0
blurred = cv2.filter2D(img, -1, box)

# separable filter (Gaussian) — faster than 2D
kx = cv2.getGaussianKernel(5, 1.0)         # 5x1
ky = cv2.getGaussianKernel(5, 1.0)         # 5x1
g2d = kx @ ky.T                            # 5x5
out2 = cv2.filter2D(img, -1, g2d)
07

형태학적 연산

Erosion과 Dilation

Erosion은 전경(흰색) 영역을 줄이고 작은 노이즈 반점을 제거하며, dilation은 늘리고 작은 구멍을 채웁니다. 커널 형태가 중요합니다. 일반용 RECT, 더 둥근 피처 ELLIPSE, 축을 따라 얇게/연결할 때 CROSS. iterations=N은 연산을 N번 반복하며 더 큰 커널을 쓰는 것과 등가입니다.

opencv
import cv2
import numpy as np

img = cv2.imread("shape.png", cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

kernel = np.ones((5, 5), np.uint8)

# erosion: shrinks white regions (removes small noise)
eroded = cv2.erode(binary, kernel, iterations=1)

# dilation: grows white regions (fills small holes)
dilated = cv2.dilate(binary, kernel, iterations=1)

# custom kernel shapes
rect = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
cross = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
ellipse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))

Opening과 Closing

Opening(erode→dilate)은 큰 객체의 크기를 바꾸지 않고 작은 밝은 반점을 제거합니다. Closing(dilate→erode)은 작은 어두운 구멍을 채웁니다. 멱등이므로 두 번 적용이 한 번과 같습니다. 고전적 노이즈 제거 패턴은 두 종류의 결함을 다루는 close-then-open(또는 open-then-close)입니다.

opencv
import cv2
import numpy as np

img = cv2.imread("noisy.png", cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

kernel = np.ones((5, 5), np.uint8)

# opening = erode then dilate -> removes small foreground noise
opened = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)

# closing = dilate then erode -> fills small holes in foreground
closed = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)

# typical denoise pipeline: open then close
clean = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)
clean = cv2.morphologyEx(clean, cv2.MORPH_OPEN, kernel)

형태학적 Gradient

형태학적 gradient(dilation - erosion)는 객체 경계의 두꺼운 외곽선을 만듭니다. 빠른 엣지 검출기나 세그먼테이션용 마스크로 유용합니다. Canny와 달리 채워지고 넓은 모서리를 주므로 정확한 모서리 위치 측정보다 영역 강조에 적합합니다.

opencv
import cv2
import numpy as np

img = cv2.imread("shape.png", cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

kernel = np.ones((5, 5), np.uint8)

# gradient = dilation - erosion -> outlines of objects
gradient = cv2.morphologyEx(binary, cv2.MORPH_GRADIENT, kernel)

# on a grayscale image (works too)
gray_grad = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel)

Top Hat과 Black Hat

top-hat은 커널보다 작은 작은 밝은 구조(예: 어두운 문서의 텍스트)를 추출하고, black-hat은 작은 어두운 구조를 추출합니다. 함께 그림자/하이라이트 추출과 빠른 불균일 조도 보정기(문서 스캐너에서 흔한 배경 나누기 트릭)로 쓰입니다.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

kernel = np.ones((15, 15), np.uint8)

# top hat = image - opening -> small bright features on dark bg
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)

# black hat = closing - image -> small dark features on bright bg
blackhat = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel)

# use case: correct uneven illumination
# background = large closing; divide image by background
bg = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
corrected = cv2.divide(img, bg, scale=255)

골격화

형태학적 골격화는 이진 형상을 1픽셀 폭의 중심축으로 얇게 만듭니다. OCR, 지문, 혈관 분석에 유용합니다. 반복 erode-빼기-open 루프가 이미지가 빌 때까지 실행됩니다. 프로덕션용으로는 scikit-image의 medial_axis나 thinning이 더 빠르고 깨끗한 결과를 줍니다.

opencv
import cv2
import numpy as np

img = cv2.imread("shape.png", cv2.IMREAD_GRAYSCALE)
_, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

# skeleton via iterative morphological opening
kernel = np.ones((3, 3), np.uint8)
skeleton = np.zeros_like(img)

while True:
    eroded = cv2.erode(img, kernel)
    opened = cv2.morphologyEx(eroded, cv2.MORPH_OPEN, kernel)
    temp = cv2.subtract(eroded, opened)
    skeleton = cv2.bitwise_or(skeleton, temp)
    img = eroded
    if cv2.countNonZero(img) == 0:
        break

Hit-or-Miss

hit-or-miss가 형태학적 패턴 매처입니다. 전경과 배경 픽셀의 정확한 구성을 찾아 코너나 T자 교차 같은 특정 형상 검출에 유용합니다. 커널은 필수 전경에 1, 필수 배경에 -1, 무관에 0을 씁니다. 틈새 용도지만 정확한 패턴 위치 찾기에는 타의를 추종하지 않습니다.

opencv
import cv2
import numpy as np

img = cv2.imread("pattern.png", cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

# hit-or-miss finds exact patterns
# kernel encodes foreground (1), background (-1), don't-care (0)
kernel = np.array([[ 0,  1, -1],
                   [ 1, -1, -1],
                   [ 1,  1,  0]], dtype=np.int32)

hits = cv2.morphologyEx(binary, cv2.MORPH_HITMISS, kernel)

# count matching locations
ys, xs = np.where(hits > 0)
print(f"found {len(xs)} matches")
08

엣지 검출

Canny 엣지 검출기

Canny가 가장 많이 쓰이는 엣지 검출기입니다. 가우시안 스무딩 → Sobel 그래디언트 → 비최대 억제 → 히스테리시스(두 임계값). 높은 임계값 위 픽셀은 엣지이고, 낮은 것과 높은 것 사이는 강한 엣지에 연결된 경우만 엣지입니다. 자동 임계값 트릭(median × 0.7/1.3)이 다양한 이미지에서 잘 동작합니다.

opencv
import cv2

img = cv2.imread("photo.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# Canny(image, threshold1, threshold2, apertureSize, L2gradient)
edges = cv2.Canny(blurred, 50, 150)

# auto-tuned thresholds from the median intensity
v = np.median(blurred)
lower = int(max(0, 0.7 * v))
upper = int(min(255, 1.3 * v))
auto = cv2.Canny(blurred, lower, upper)

# L2 gradient (more accurate, slower)
edges_l2 = cv2.Canny(blurred, 50, 150, L2gradient=True)

Sobel 연산자

Sobel은 1차 도함수를 계산하며 음의 그래디언트를 담으려 ddepth=cv2.CV_64F(또는 CV_16S)를 쓰세요. 아니면 uint8 오버플로가 어두움→밝음 전이를 보이지 않게 만듭니다. ksize=3이 표준이고, ksize=5는 더 부드럽지만 넓은 엣지를 줍니다. 크기(sqrt(sx²+sy²))가 Canny와 많은 피처 검출기의 기반입니다.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

# Sobel x (vertical edges)
sx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3)

# Sobel y (horizontal edges)
sy = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3)

# gradient magnitude
mag = np.sqrt(sx**2 + sy**2)
mag = np.uint8(255 * mag / mag.max())

# gradient direction (for non-max suppression)
angle = np.arctan2(sy, sx)

# convert back to visible uint8
sx_abs = cv2.convertScaleAbs(sx)
sy_abs = cv2.convertScaleAbs(sy)

Laplacian

Laplacian은 2차 도함수이며 노이즈에 매우 민감하므로 항상 먼저 블러하세요. 영교차(부호 변화)를 검출해 얇고 정밀한 엣지를 주지만 방향은 없습니다. 주로 Marr-Hildreth 엣지 검출과 이미지 샤프닝의 'L' 채널 입력(언샵 마스크)으로 쓰입니다. 2차 도함수는 크게 음으로 흔들리므로 CV_64F를 쓰세요.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)
blurred = cv2.GaussianBlur(img, (3, 3), 0)

# Laplacian: second derivative in both directions
lap = cv2.Laplacian(blurred, cv2.CV_64F)
lap_abs = cv2.convertScaleAbs(lap)

# zero-crossing detection (sharper edges)
# Manual Laplacian kernel
kernel = np.array([[0,  1, 0],
                   [1, -4, 1],
                   [0,  1, 0]], dtype=np.float32)
edges = cv2.filter2D(blurred, -1, kernel)

Scharr 필터

Scharr는 3x3 윈도우용으로 설계된 Sobel 변형입니다. 작은 커널을 써야 한다면 Sobel ksize=3보다 정확한 그래디언트 방향을 줍니다. 더 큰 커널(5x5, 7x7)에는 Sobel이 충분합니다. ksize=-1인 cv2.Sobel이 Scharr과 등가입니다. 그래디언트 방향이 중요할 때(HOG, 엣지 방향) Scharr이 선호됩니다.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

# Scharr: a Sobel variant optimized for 3x3 kernels
# better rotational symmetry than 3x3 Sobel
sx = cv2.Scharr(img, cv2.CV_64F, 1, 0)
sy = cv2.Scharr(img, cv2.CV_64F, 0, 1)

mag = cv2.magnitude(sx, sy)
mag_u8 = cv2.convertScaleAbs(mag)

# equivalent to Sobel with ksize=-1
sx2 = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=-1)

엣지 검출 파이프라인

그레이스케일 → 노이즈 제거 → Canny → dilate → findContours 파이프라인이 실용적 엣지 작업의 큰 비중을 커버합니다. 컨투어 찾기 전 dilation이 그렇지 않으면 하나의 객체를 여러 개로 쪼개는 끊어진 엣지를 닫습니다. Canny 임계값과 노이즈 제거 커널 크기 튜닝에 대부분의 엔지니어링 노력이 들어갑니다.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")

# 1. grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 2. denoise (Gaussian or bilateral)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# 3. auto-thresholded Canny
v = np.median(blurred)
edges = cv2.Canny(blurred, int(0.7 * v), int(1.3 * v))

# 4. dilate to close gaps, then find contours
edges = cv2.dilate(edges, np.ones((3, 3), np.uint8), iterations=1)
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)

# 5. filter by area
out = img.copy()
for c in contours:
    if cv2.contourArea(c) > 100:
        cv2.drawContours(out, [c], -1, (0, 255, 0), 2)

cv2.imshow("edges", edges)
cv2.imshow("contours", out)
cv2.waitKey(0)
09

컨투어

컨투어 찾기

findContours는 OpenCV 3.x에서 소스 이미지를 수정하므로 이진 이미지가 필요하면 복사본을 전달하세요. RETR_EXTERNAL은 가장 바깥 컨투어만 반환하고(가장 빠름) RETR_TREE는 (객체 내부 구멍 같은) 중첩 형상의 전체 계층을 줍니다. CHAIN_APPROX_SIMPLE이 직선을 따라 중복 점을 버려 메모리를 아낍니다.

opencv
import cv2

img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# findContours(image, mode, method)
# mode: RETR_EXTERNAL (outer only), RETR_LIST, RETR_TREE, RETR_CCOMP
# method: CHAIN_APPROX_SIMPLE compresses horizontal/vertical/diagonal segments
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                                       cv2.CHAIN_APPROX_SIMPLE)

print(f"found {len(contours)} contours")
# hierarchy is shape (1, N, 4): [next, prev, child, parent]

# OpenCV 3 returns (image, contours, hierarchy)
# OpenCV 4 returns (contours, hierarchy)

컨투어 그리기

drawContours(image, contours, contourIdx, color, thickness): contourIdx=-1은 모두, 특정 인덱스는 하나를 그립니다. thickness=-1은 컨투어를 채웁니다. 빈 이미지에 그리는 것이 평균 색이나 마스크된 히스토그램 같은 다운스트림 연산용 컨투어 마스크를 만드는 표준 방법입니다.

opencv
import cv2

img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)

# draw all contours (-1), color, thickness
cv2.drawContours(img, contours, -1, (0, 255, 0), 2)

# draw a single contour by index
cv2.drawContours(img, contours, 0, (0, 0, 255), 3)

# filled contour (thickness = -1)
cv2.drawContours(img, contours, -1, (255, 0, 0), -1)

# draw on a blank canvas (mask)
mask = np.zeros_like(gray)
cv2.drawContours(mask, contours, -1, 255, -1)

컨투어 속성

contourArea는 픽셀 단위이며 구멍을 무시합니다(순 면적에는 RETR_CCOMP 계층의 컨투어를 쓰세요). moments 딕셔너리가 무게중심(m10/m00, m01/m00)을 주며, m00이 0이면(퇴화 컨투어) 0 나눗셈을 가드하세요. 종횡비와 extent가 형상 분류의 가장 단순한 형상 서술자입니다.

opencv
import cv2

img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)

for c in contours:
    area = cv2.contourArea(c)             # area in pixels
    peri = cv2.arcLength(c, True)         # perimeter (closed=True)
    M = cv2.moments(c)                     # spatial moments
    cx = int(M['m10'] / M['m00'])          # centroid x
    cy = int(M['m01'] / M['m00'])          # centroid y

    # bounding box
    x, y, w, h = cv2.boundingRect(c)
    aspect = w / float(h)                 # aspect ratio
    extent = area / float(w * h)          # filled area ratio

    print(f"area={area:.0f} peri={peri:.1f} center=({cx},{cy}) aspect={aspect:.2f}")

경계 사각형

boundingRect는 축 정렬 박스를 주고(빠르고 단순) minAreaRect는 가장 작은 회전 사각형을 줍니다(객체의 진짜 방향/크기 측정에 유용). boxPoints가 회전 사각형을 drawContours에 넘길 수 있는 4개 코너 점으로 변환합니다. minEnclosingCircle은 컨투어를 포함하는 가장 작은 원입니다.

opencv
import cv2

img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)

for c in contours:
    # axis-aligned bounding rectangle
    x, y, w, h = cv2.boundingRect(c)
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)

    # minimum area (rotated) rectangle
    rect = cv2.minAreaRect(c)             # ((cx, cy), (w, h), angle)
    box = cv2.boxPoints(rect)             # 4 corner points
    box = np.int0(box)
    cv2.drawContours(img, [box], 0, (0, 0, 255), 2)

    # minimum enclosing circle
    (cx, cy), r = cv2.minEnclosingCircle(c)
    cv2.circle(img, (int(cx), int(cy)), int(r), (255, 0, 0), 2)

컨투어 근사

approxPolyDP는 Douglas-Peucker 알고리즘으로 컨투어를 더 적은 정점의 다각형으로 단순화합니다. epsilon(보통 둘레의 1~5%)이 허용 오차를 제어하며 작을수록 더 많은 디테일을 유지합니다. 정점 세기가 고전적 수제 형상 분류기입니다. 삼각형=3, 사각형=4, 원=많음.

opencv
import cv2

img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)

for c in contours:
    peri = cv2.arcLength(c, True)
    # approxPolyDP: simplify the contour to fewer vertices
    eps = 0.04 * peri                      # 4% of perimeter
    approx = cv2.approxPolyDP(c, eps, True)

    n = len(approx)
    if n == 3:
        label = "triangle"
    elif n == 4:
        label = "rectangle"
    elif n == 5:
        label = "pentagon"
    else:
        label = f"{n}-gon"

    cv2.drawContours(img, [approx], -1, (0, 255, 0), 2)
    cv2.putText(img, label, tuple(approx[0][0]),
                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)

Convex Hull과 결함

convex hull은 컨투어를 감싸는 가장 작은 볼록 형상으로, 객체 밀집도 측정과 convexity defect를 통한 손/손가락 검출에 유용합니다. 각 결함의 깊이가 컨투어가 hull에 비해 얼마나 '안쪽으로' 들어가는지 측정하며, 손 실루엣의 깊은 결함은 보통 손가락 사이 간격에 해당합니다.

opencv
import cv2

img = cv2.imread("hand.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)
c = max(contours, key=cv2.contourArea)

# convex hull (smallest convex polygon enclosing the contour)
hull = cv2.convexHull(c)
cv2.drawContours(img, [hull], -1, (0, 255, 0), 2)

# convexity defects (gaps between contour and hull) — needs returnPoints=False
hull_idx = cv2.convexHull(c, returnPoints=False)
defects = cv2.convexityDefects(c, hull_idx)
# defects[i] = (start, end, far, depth) — depth in 1/256 of peri

# is the contour convex?
is_convex = cv2.isContourConvex(c)
10

임계값 처리

기본 임계값

THRESH_BINARY: 위→255, 아래→0. THRESH_TRUNC: 위→thresh로 제한, 아래→변경 없음. THRESH_TOZERO: 위→변경 없음, 아래→0. 반환된 ret은 단순 임계값 처리에서는 입력 임계값과 같지만 Otsu/Triangle에서 의미를 갖습니다. 범위 밖 픽셀을 어떻게 다룰지에 따라 타입을 고르세요.

opencv
import cv2

img = cv2.imread("doc.png", cv2.IMREAD_GRAYSCALE)

# threshold(src, thresh, maxval, type)
# returns (retval, binary_image)
ret, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

# threshold types
_, inv     = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
_, trunc   = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)
_, tozero  = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)
_, tozero_inv = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)

# ret is the threshold actually used (useful with Otsu)

적응형 임계값

적응형 임계값 처리는 각 픽셀의 지역 이웃을 기반으로 서로 다른 임계값을 계산합니다. 불균일 조도의 이미지(예: 문서 사진)에 필수입니다. blockSize는 홀수여야 하며(보통 11~31) 피처 크기보다 커야 합니다. C가 지역 평균에서 상수를 빼며, 저대비 노이즈를 억제하려 올리세요.

opencv
import cv2

img = cv2.imread("doc.png", cv2.IMREAD_GRAYSCALE)
img = cv2.medianBlur(img, 5)

# adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C)
# adaptiveMethod:
#   ADAPTIVE_THRESH_MEAN_C  -> mean of neighborhood minus C
#   ADAPTIVE_THRESH_GAUSSIAN_C -> weighted mean minus C
adap_mean = cv2.adaptiveThreshold(img, 255,
    cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)

adap_gauss = cv2.adaptiveThreshold(img, 255,
    cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

Otsu 방법

Otsu 방법은 전경/배경 클래스 간 분산을 최대화하는 최적 전역 임계값을 찾습니다. thresh=0을 주고 THRESH_OTSU 플래그를 더하세요. 항상 먼저 블러하세요. Otsu는 히스토그램 노이즈에 민감합니다. Triangle 방법은 (현미경처럼) 지배적 피크가 하나인 이미지에서 더 잘 동작합니다. 반환된 ret이 계산된 임계값입니다.

opencv
import cv2

img = cv2.imread("doc.png", cv2.IMREAD_GRAYSCALE)
blurred = cv2.GaussianBlur(img, (5, 5), 0)

# Otsu: automatically picks the threshold that maximizes between-class variance
ret, otsu = cv2.threshold(blurred, 0, 255,
                          cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print(f"Otsu threshold: {ret}")

# Triangle method (good for skewed histograms / single peak)
ret_t, tri = cv2.threshold(blurred, 0, 255,
                           cv2.THRESH_BINARY + cv2.THRESH_TRIANGLE)
print(f"Triangle threshold: {ret_t}")

색 임계값 (inRange)

inRange가 표준 색 분할 도구입니다. 색(hue)과 밝기를 분리해 임계값이 조명 변화에 강해지므로 먼저 HSV로 변환하세요. 빨강 hue가 0/180을 감싸므로 두 마스크를 OR해야 합니다. 마스크의 노이즈 반점을 줄이려 inRange 전에 항상 블러하세요.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# detect a range of green pixels
lower = np.array([35, 50, 50])
upper = np.array([85, 255, 255])
mask = cv2.inRange(hsv, lower, upper)

# apply mask to the original
result = cv2.bitwise_and(img, img, mask=mask)

# hue wraps around for red (0-10 and 170-180)
mask1 = cv2.inRange(hsv, np.array([0, 50, 50]),   np.array([10, 255, 255]))
mask2 = cv2.inRange(hsv, np.array([170, 50, 50]), np.array([180, 255, 255]))
red_mask = cv2.bitwise_or(mask1, mask2)

임계값 파이프라인

노이즈 제거 → 임계값 → 형태학 파이프라인이 대부분의 이진화 작업을 처리합니다. 균일 조도에는 Otsu, 불균일에는 적응형을 고르세요. 형태학적 close-then-open이 내부 구멍과 외부 반점을 모두 제거합니다. 항상 이진 마스크를 검사하세요. 임계값 파라미터는 거의 항상 이미지별로 다르며 데이터셋마다 튜닝이 필요합니다.

opencv
import cv2
import numpy as np

img = cv2.imread("doc.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 1. denoise
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# 2. choose a method
#    - flat lighting    -> Otsu
#    - uneven lighting  -> adaptive
#    - document scan    -> adaptive Gaussian
if lighting == "flat":
    _, binary = cv2.threshold(blurred, 0, 255,
                              cv2.THRESH_BINARY + cv2.THRESH_OTSU)
else:
    binary = cv2.adaptiveThreshold(blurred, 255,
        cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 5)

# 3. morphology cleanup
kernel = np.ones((3, 3), np.uint8)
binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)
binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)

OCR을 위한 이진화

OCR에서는 불균일 조도 때문에 적응형 가우시안이 촬영 문서의 전역 Otsu를 거의 항상 이깁니다. blockSize를 문자 높이에 맞추세요(경험칙: 획 폭 1~2배 × 4). 대부분의 OCR 엔진(Tesseract)은 흰 배경에 검은 텍스트를 선호하므로 이진 이미지가 반대면 반전하세요.

opencv
import cv2

img = cv2.imread("text.png", cv2.IMREAD_GRAYSCALE)

# adaptive Gaussian with a block size matched to character height
# (e.g. char ~25 px -> blockSize ~31)
binary = cv2.adaptiveThreshold(img, 255,
    cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 10)

# invert if needed (OCR often prefers black-on-white)
binary_inv = cv2.bitwise_not(binary)

# Otsu on a preprocessed image as an alternative
blur = cv2.GaussianBlur(img, (3, 3), 0)
_, otsu = cv2.threshold(blur, 0, 255,
                        cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
11

색 공간

BGR / RGB / Gray

OpenCV는 기본적으로 BGR로 이미지를 읽지만 대부분의 다른 라이브러리(matplotlib, PIL, scikit-image)는 RGB를 씁니다. cvtColor를 잊는 것이 '빨강과 파랑이 뒤바뀐' 이미지의 가장 흔한 원인입니다. 그레이스케일 변환은 단순 평균이 아니라 지각 가중치를 씁니다(Y = 0.299R + 0.587G + 0.114B).

opencv
import cv2

bgr = cv2.imread("photo.jpg")           # OpenCV default: BGR

# BGR -> RGB (for matplotlib, PIL, etc.)
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)

# BGR -> grayscale (luminance-weighted)
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)

# RGB -> BGR (reverse)
bgr2 = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)

# grayscale -> BGR (replicates channel, color image with no color)
bgr_from_gray = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)

BGR → HSV

OpenCV의 HSV는 uint8에 들어가도록 H를 0-179로 씁니다(0-360 아님). 다른 라이브러리 코드를 포팅할 때 2배 어긋남 버그의 잦은 원천입니다. S와 V는 0-255입니다. HSV가 색 기반 분할의 기본 공간이며 hue가 밝기 변화에 대략 불변이므로 색으로 객체 추적에 쓰세요.

opencv
import cv2
import numpy as np

bgr = cv2.imread("photo.jpg")
hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)

# split channels
h, s, v = cv2.split(hsv)

# HSV ranges in OpenCV: H: 0-179, S: 0-255, V: 0-255
# (H is halved so it fits in 8-bit — full hue circle is 0-360)
print(h.max(), s.max(), v.max())   # 179 255 255

# back to BGR
bgr2 = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)

BGR → LAB

CIELAB은 인간 지각을 근사합니다. 같은 수치 변화가 대략 같게 다르게 보여 색차 지표(ΔE)에 쓰입니다. L 채널이 밝기만 인코딩하므로 L 편집이 색을 이동시키지 않고 이미지를 밝히는 가장 깨끗한 방법입니다. OpenCV의 LAB은 L의 표준 0-100이 아니라 모든 채널에 0-255를 씁니다.

opencv
import cv2

bgr = cv2.imread("photo.jpg")

# BGR -> LAB (perceptually uniform color space)
lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB)
L, A, B = cv2.split(lab)

# L: lightness (0-255), A: green<->red, B: blue<->yellow
# useful for separating luminance from color

# LAB is great for color-difference metrics (delta-E)
# and for editing lightness without affecting color
import numpy as np
lab_bright = lab.copy()
lab_bright[:, :, 0] = np.clip(lab_bright[:, :, 0].astype(int) + 30, 0, 255)
bgr_bright = cv2.cvtColor(lab_bright, cv2.COLOR_LAB2BGR)

색 추적 (HSV)

HSV 기반 색 추적이 가장 단순한 객체 추적기입니다. hue 범위를 정하고, 임계값을 적용하고, 가장 큰 블롭을 찾습니다. 나쁜 조명(낮은 채도), 비슷한 색의 배경 객체, 반사 표면에서 실패합니다. 견고한 추적에는 (hue 히스토그램 역투영을 쓰는) camshift/meanshift를 결합하거나 움직임을 부드럽게 하는 칼만 필터를 쓰세요.

opencv
import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if not ret:
        break

    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # track a blue object
    lower = np.array([100, 80, 80])
    upper = np.array([130, 255, 255])
    mask = cv2.inRange(hsv, lower, upper)

    # find the largest blob
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,
                                   cv2.CHAIN_APPROX_SIMPLE)
    if contours:
        c = max(contours, key=cv2.contourArea)
        if cv2.contourArea(c) > 500:
            (x, y), r = cv2.minEnclosingCircle(c)
            cv2.circle(frame, (int(x), int(y)), int(r), (0, 255, 255), 2)

    cv2.imshow("frame", frame)
    cv2.imshow("mask", mask)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()

채널 분리와 병합

split/merge는 편리하지만 NumPy 인덱싱보다 느립니다. img[:, :, 0]이 파란 채널이며 수정이 split보다 빠릅니다. 대상 색 공간에 맞는 올바른 순서로 merge에 채널을 전달하세요. '두 채널을 0으로' 트릭이 단일 색상 채널의 기여를 시각화하는 고전적 방법입니다.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")

# split into B, G, R channels (each is a 2-D array)
b, g, r = cv2.split(img)

# merge channels back (order matters!)
merged = cv2.merge([b, g, r])

# zero out one channel to visualize
zeros = np.zeros_like(b)
blue_only  = cv2.merge([b, zeros, zeros])
green_only = cv2.merge([zeros, g, zeros])
red_only   = cv2.merge([zeros, zeros, r])

# swap channels (e.g. fake RGB->BGR by swapping R and B)
swapped = cv2.merge([r, g, b])

기타 색 공간

YCrCb는 휘도(Y)를 색차(Cr, Cb)와 분리합니다. JPEG와 MPEG 압축의 기반으로, 인간은 색보다 밝기에 덜 민감해 색차 디테일을 버립니다. HLS는 포화와 무관하게 흰색이 L=1이라는 점에서 HSV와 다르며 일부 음영 효과에 더 낫습니다. 신경 쓰지 않을 것에 불변인 연산을 만드는 공간을 고르세요.

opencv
import cv2

bgr = cv2.imread("photo.jpg")

# YCrCb (used in JPEG compression)
ycrcb = cv2.cvtColor(bgr, cv2.COLOR_BGR2YCrCb)

# HLS (Hue, Lightness, Saturation — alternative to HSV)
hls = cv2.cvtColor(bgr, cv2.COLOR_BGR2HLS)

# YUV (used in video encoding)
yuv = cv2.cvtColor(bgr, cv2.COLOR_BGR2YUV)

# grayscale -> all spaces start from BGR, so chain conversions
gray_from_ycrcb = cv2.cvtColor(ycrcb, cv2.COLOR_YCrCb2BGR)
gray = cv2.cvtColor(gray_from_ycrcb, cv2.COLOR_BGR2GRAY)
12

히스토그램

히스토그램 계산

calcHist는 이미지 목록, 채널 목록, 선택적 마스크(None = 전체 이미지), bin 수, 값 범위를 받습니다. 다차원 히스토그램(예: 2차원 hue-채도)에는 두 채널과 두 bin 크기를 전달하며 색 추적의 히스토그램 역투영에 쓰입니다. 각 채널의 히스토그램은 독립적으로 계산됩니다.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

# calcHist(images, channels, mask, histSize, ranges)
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
print(hist.shape)   # (256, 1)

# normalize to 0-1
hist /= hist.sum()

# multi-channel histogram (color)
bgr = cv2.imread("photo.jpg")
colors = ('b', 'g', 'r')
for i, col in enumerate(colors):
    h = cv2.calcHist([bgr], [i], None, [256], [0, 256])

히스토그램 플롯

히스토그램 시각화에는 matplotlib이 가장 쉽습니다. 하지만 범례 색이 채널 레이블과 맞도록 BGR을 RGB로 변환하세요. 왼쪽으로 치우친 히스토그램은 어두운 이미지, 오른쪽은 밝은 이미지, 좁은 스파이크는 낮은 대비입니다. 노출과 화이트밸런스 문제 진단에 쓰세요.

opencv
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread("photo.jpg")
colors = ('b', 'g', 'r')
for i, col in enumerate(colors):
    hist = cv2.calcHist([img], [i], None, [256], [0, 256])
    plt.plot(hist, color=col)
    plt.xlim([0, 256])

plt.title("Color Histogram")
plt.xlabel("Pixel value")
plt.ylabel("Frequency")
plt.show()

히스토그램 평활화

히스토그램 평활화는 픽셀 강도를 0-255 전체로 늘립니다. 저대비 이미지에 좋지만 하이라이트를 날리고 노이즈를 증폭할 수 있습니다. BGR 세 채널을 직접 평활화하지 마세요. 색이 이동합니다. 항상 휘도/색차 공간(YCrCb, LAB, HSV)으로 변환해 휘도를 평활화한 뒤 되돌리세요.

opencv
import cv2

img = cv2.imread("dark.jpg", cv2.IMREAD_GRAYSCALE)

# global histogram equalization
eq = cv2.equalizeHist(img)

# equalization on color images: convert to YCrCb, equalize Y only
bgr = cv2.imread("color.jpg")
ycrcb = cv2.cvtColor(bgr, cv2.COLOR_BGR2YCrCb)
ycrcb[:, :, 0] = cv2.equalizeHist(ycrcb[:, :, 0])
eq_color = cv2.cvtColor(ycrcb, cv2.COLOR_YCrCb2BGR)

CLAHE (적응형 평활화)

CLAHE가 전역 평활화의 프로덕션 품질 대안입니다. 작은 타일로 동작해 불균일 조도 이미지에서도 동작하고, clipLimit가 대비 증폭을 제한해 노이즈 폭발을 피합니다. tileGridSize 8x8이 기본이며 타일이 작을수록 지역 적응이 커집니다. 의료 영상과 문서 개선의 기본 선택입니다.

opencv
import cv2

img = cv2.imread("dark.jpg", cv2.IMREAD_GRAYSCALE)

# CLAHE: Contrast Limited Adaptive Histogram Equalization
# equalizes small tiles, limiting amplification of noise
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
enhanced = clahe.apply(img)

# on color: equalize the L channel of LAB
bgr = cv2.imread("color.jpg")
lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB)
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))
lab[:, :, 0] = clahe.apply(lab[:, :, 0])
enhanced_color = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)

히스토그램 역투영

히스토그램 역투영은 '어디 픽셀이 내 ROI의 색 분포처럼 보이는가?'에 답합니다. 샘플로 2차원 hue-채도 히스토그램을 만든 뒤 대상 이미지에 역투영해 확률 맵을 얻습니다. meanShift/camShift 추적의 기반이며 대상의 실제 색 분포를 학습하므로 고정 HSV 범위보다 훨씬 견고합니다.

opencv
import cv2
import numpy as np

img = cv2.imread("scene.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# take a small ROI of the target color (the object to track)
roi = hsv[100:150, 100:150]
roi_hist = cv2.calcHist([roi], [0, 1], None, [180, 256], [0, 180, 0, 256])
cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)

# backproject: each pixel = probability of belonging to the ROI's color
backproj = cv2.calcBackProject([hsv], [0, 1], roi_hist, [0, 180, 0, 256], 1)

# denoise and threshold
disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
backproj = cv2.filter2D(backproj, -1, disc)
_, mask = cv2.threshold(backproj, 50, 255, cv2.THRESH_BINARY)

result = cv2.bitwise_and(img, img, mask=mask)
13

피처 검출

Harris 코너 검출기

Harris는 작은 윈도우를 어떤 방향으로 옮기든 큰 강도 변화가 있는지 검사해 코너를 검출합니다. 코너는 모든 방향에서, 엣지는 한 방향에서, 평탄 영역은 어느 방향에서도 변하지 않습니다. 출력은 코너 응답 맵이며 최대값 기준 임계값을 적용합니다(예: 0.01 * max). blockSize가 구조 텐서 계산의 이웃입니다.

opencv
import cv2
import numpy as np

img = cv2.imread("chessboard.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# cornerHarris(gray, blockSize, ksize, k)
# blockSize: neighborhood for corner detection
# ksize:     Sobel aperture (3, 5, 7)
# k:         Harris free parameter (0.04 - 0.06)
dst = cv2.cornerHarris(gray, 2, 3, 0.04)

# dilate to mark corners
dst = cv2.dilate(dst, None)

# threshold and mark in red
img[dst > 0.01 * dst.max()] = [0, 0, 255]

Shi-Tomasi (goodFeaturesToTrack)

Shi-Tomasi는 점수로 min(고유값1, 고유값2)을 써 Harris를 개선하며 추적에 더 안정적인 코너를 줍니다. maxCorners가 개수를 제한하고, qualityLevel은 가장 강한 코너 응답의 비율이며(0.01 = 최선의 1%), minDistance가 검출된 코너의 공간 분리를 강제합니다. Lucas-Kanade 광학 흐름 추적기의 기본 입력입니다.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# goodFeaturesToTrack returns the N strongest corners
corners = cv2.goodFeaturesToTrack(gray, maxCorners=100,
                                  qualityLevel=0.01,
                                  minDistance=10)
corners = np.int0(corners)

for c in corners:
    x, y = c.ravel()
    cv2.circle(img, (x, y), 3, (0, 0, 255), -1)

SIFT (스케일 불변 피처)

SIFT는 스케일과 회전에 불변인 키포인트와 각각의 128차원 서술자를 찾습니다. 조명, 시점, 부분 가림에 강건합니다. 수년간 특허받았다가 OpenCV 4.4에서 자유가 됐습니다. 속도보다 정확도가 중요한 매칭에 SIFT를 쓰세요. DRAW_RICH_KEYPOINTS가 각 키포인트의 스케일과 방향을 그립니다.

opencv
import cv2

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

# SIFT was patented; free since OpenCV 4.4 (contrib not required)
sift = cv2.SIFT_create()

# detect keypoints
kp = sift.detect(img, None)

# detect and compute descriptors
kp, des = sift.detectAndCompute(img, None)
print(len(kp), des.shape)   # N, (N, 128)

# draw keypoints
out = cv2.drawKeypoints(img, kp, None,
                        flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

ORB (FAST + BRIEF)

ORB는 FAST 키포인트 검출기와 BRIEF 서술자를 결합합니다. 둘 다 특허가 없고 SIFT보다 약 10배 빨라 모바일/임베디드 실시간 매칭의 표준 선택입니다. 서술자가 이진입니다(32바이트 vs SIFT의 128 float) 그래서 매칭은 해밍 거리를 씁니다. 스케일/회전에서 SIFT보다 약간 덜 강건하지만 비용 대비 탁월합니다.

opencv
import cv2

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

# ORB: free, fast alternative to SIFT
orb = cv2.ORB_create(nfeatures=1000)

kp, des = orb.detectAndCompute(img, None)
print(len(kp), des.shape)   # N, (N, 32) — binary descriptors

# draw keypoints
out = cv2.drawKeypoints(img, kp, None, color=(0, 255, 0),
                        flags=0)

# FAST alone (detector only, no descriptor)
fast = cv2.FastFeatureDetector_create(threshold=20)
kp = fast.detect(img, None)

FAST 검출기

FAST는 후보 주위 16픽셀 원에 중심보다 모두 밝거나 모두 어두운 연속 N픽셀이 있는지 검사합니다. 조기 종단 때문에 극도로 빠릅니다. 키포인트만 반환하며 서술자가 없습니다(서술자는 BRIEF나 ORB). 낮은 임계값 = 더 많고(노이즈한) 코너. 비최대 억제가 지역 최대값의 중복을 제거합니다.

opencv
import cv2

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

# FAST: speed-optimized corner detector (detector only)
fast = cv2.FastFeatureDetector_create(threshold=20,
                                      nonmaxSuppression=True)

kp = fast.detect(img, None)
print(f"{len(kp)} keypoints")

# tune the threshold
fast.setThreshold(30)
print(f"threshold is now {fast.getThreshold()}")

# turn off non-max suppression to get more (clustered) corners
fast.setNonmaxSuppression(False)
kp_all = fast.detect(img, None)

MSER (최대 안정 극값 영역)

MSER은 다양한 강도 임계값에서 안정적으로 유지되는 영역을 찾습니다. 텍스트 검출(글자가 블롭형), 번호판, 장면 텍스트에 이상적입니다. 각 영역이 자기 임계값에서 검출되므로 불균일 조명을 잘 다룹니다. 명백한 비텍스트를 제거하려 종횡비와 크기로 결과를 필터하세요.

opencv
import cv2

img = cv2.imread("text.jpg", cv2.IMREAD_GRAYSCALE)

# MSER: detects stable connected regions across thresholds
mser = cv2.MSER_create()
regions, _ = mser.detectRegions(img)

# regions is a list of point arrays
out = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
for pts in regions:
    x, y, w, h = cv2.boundingRect(pts)
    if 5 < h < 50:    # filter by likely text size
        cv2.rectangle(out, (x, y), (x+w, y+h), (0, 255, 0), 1)
14

피처 매칭

Brute Force 매칭

브루트 포스 매칭은 모든 서술자 쌍을 시도합니다. 정확하지만 O(N*M)입니다. ORB의 이진 서술자에는 NORM_HAMMING, SIFT/SURF의 float 서술자에는 NORM_L2를 쓰세요. crossCheck=True는 상호 최선 매칭만 유지해(A의 최선이 B이고 그 반대도) 많은 오탐을 제거합니다. 각 매칭의 .distance는 작을수록 좋습니다.

opencv
import cv2

img1 = cv2.imread("box.png", cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread("scene.png", cv2.IMREAD_GRAYSCALE)

orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)

# for ORB (binary descriptors) use Hamming distance
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)

# sort by distance (best first)
matches = sorted(matches, key=lambda m: m.distance)

# draw top 20
out = cv2.drawMatches(img1, kp1, img2, kp2, matches[:20], None,
                      flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

FLANN 매칭

FLANN(Fast Library for Approximate Nearest Neighbors)은 (SIFT/SURF용) KD-tree나 (ORB용) LSH를 만들어 근사 매칭을 찾습니다. 큰 서술자 집합에서 브루트 포스보다 훨씬 빠르지만 때때로 놓칩니다. trees와 checks 파라미터가 정확도와 속도를 절충합니다. 수천 개 피처에는 FLANN, 작은 집합에는 브루트 포스로 충분합니다.

opencv
import cv2
import numpy as np

img1 = cv2.imread("box.png", cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread("scene.png", cv2.IMREAD_GRAYSCALE)

sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)

# FLANN parameters for SIFT (float descriptors)
FLANN_INDEX_KDTREE = 1
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)
flann = cv2.FlannBasedMatcher(index_params, search_params)

matches = flann.knnMatch(des1, des2, k=2)

KNN 매칭과 비율 테스트

Lowe의 비율 테스트가 피처 매칭의 표준 필터입니다. 최선 매칭이 차선보다 훨씬 가까울 때만 유지하세요(전형 임계값 0.7~0.8). 직관: 두 후보가 비슷하게 가까우면 매칭은 모호하고 아마 틀렸습니다. 이 단일 테스트가 대부분의 오탐을 제거합니다.

opencv
import cv2

img1 = cv2.imread("box.png", cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread("scene.png", cv2.IMREAD_GRAYSCALE)

sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)

bf = cv2.BFMatcher(cv2.NORM_L2)
matches = bf.knnMatch(des1, des2, k=2)   # 2 nearest neighbors

# Lowe's ratio test: keep only unambiguous matches
good = []
for m, n in matches:
    if m.distance < 0.75 * n.distance:
        good.append(m)

out = cv2.drawMatches(img1, kp1, img2, kp2, good, None,
                      flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

호모그래피 (RANSAC)

RANSAC과 함께 쓴 findHomography는 이상값을 무시하며 src를 dst로 매핑하는 원근 변환을 계산합니다. inlier 마스크가 어떤 매칭이 모델과 일치하는지 알려 줍니다. 재투영 임계값(5.0)은 픽셀 단위이며 낮을수록 엄격합니다. 좋은 매칭이 최소 4개 필요합니다. 장면에서 알려진 객체를 위치시키거나 겹치는 사진을 정렬하는 데 쓰세요.

opencv
import cv2
import numpy as np

img1 = cv2.imread("box.png", cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread("scene.png", cv2.IMREAD_GRAYSCALE)

sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)

bf = cv2.BFMatcher(cv2.NORM_L2)
matches = bf.knnMatch(des1, des2, k=2)
good = [m for m, n in matches if m.distance < 0.75 * n.distance]

# build point correspondences
src = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
dst = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)

# RANSAC homography
H, mask = cv2.findHomography(src, dst, cv2.RANSAC, 5.0)
inliers = mask.ravel().tolist()
print(f"{sum(inliers)} inliers / {len(good)} matches")

객체 위치 파악

이것이 고전적 객체 위치 파악 파이프라인입니다. 두 이미지에서 피처를 검출하고, 매칭하고, RANSAC으로 호모그래피를 피팅한 뒤, 객체의 경계 박스를 장면에 투영합니다. 평면 객체나 원거리 3D 객체(원근이 지배)에 동작합니다. 무텍스처, 대칭, 심하게 가려진 객체에서는 실패하며 그런 경우 딥러닝 검출기를 쓰세요.

opencv
import cv2
import numpy as np

img1 = cv2.imread("box.png", cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread("scene.png", cv2.IMREAD_GRAYSCALE)

sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)

bf = cv2.BFMatcher(cv2.NORM_L2)
good = [m for m, n in bf.knnMatch(des1, des2, k=2)
        if m.distance < 0.75 * n.distance]

src = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
dst = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)

H, _ = cv2.findHomography(src, dst, cv2.RANSAC, 5.0)

# project the object's corners into the scene
h, w = img1.shape
corners = np.float32([[0, 0], [w-1, 0], [w-1, h-1], [0, h-1]]).reshape(-1, 1, 2)
scene_corners = cv2.perspectiveTransform(corners, H)

out = cv2.cvtColor(img2, cv2.COLOR_GRAY2BGR)
cv2.polylines(out, [np.int32(scene_corners)], True, (0, 255, 0), 3)
15

얼굴 검출

Haar Cascade 분류기

Haar cascade가 고전적 Viola-Jones 검출기입니다. CPU에서 빠르고 정면 얼굴에 좋지만 현대 딥러닝 검출기(MTCNN, SSD, RetinaFace)보다 덜 정확합니다. scaleFactor(>1)가 다중 스케일 탐색을 제어하며 1.1 = 10% 스케일 단계입니다. 작을수록 느리지만 철저합니다. minNeighbors가 겹치는 검출을 필터하며 올리면 오탐이 줄어듭니다.

opencv
import cv2

# load a pretrained cascade (shipped with OpenCV)
cascade_path = cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
face_cascade = cv2.CascadeClassifier(cascade_path)

print(face_cascade.empty())   # False = loaded ok

img = cv2.imread("people.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# detectMultiScale(gray, scaleFactor, minNeighbors, minSize, maxSize)
faces = face_cascade.detectMultiScale(
    gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)

이미지에서 얼굴 검출

얼굴 ROI 안에서 눈(또는 미소)을 검출하는 것이 표준 효율 트릭입니다. 전체 이미지에서 눈을 찾으면 오탐이 많지만 확인된 얼굴 ROI 안에서는 드뭅니다. cv2.data.haarcascades가 번들 XML 디렉터리를 가리키며 다른 cascade(눈, 미소, 전신, 번호판)도 있습니다. cascade를 호출하기 '전에' ROI를 잘라내세요.

opencv
import cv2

face_cascade = cv2.CascadeClassifier(
    cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
eye_cascade = cv2.CascadeClassifier(
    cv2.data.haarcascades + "haarcascade_eye.xml")

img = cv2.imread("people.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (fx, fy, fw, fh) in faces:
    cv2.rectangle(img, (fx, fy), (fx+fw, fy+fh), (255, 0, 0), 2)

    # search for eyes INSIDE the face region (faster, fewer false positives)
    roi_gray = gray[fy:fy+fh, fx:fx+fw]
    roi_color = img[fy:fy+fh, fx:fx+fw]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (ex, ey, ew, eh) in eyes:
        cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)

비디오에서 얼굴 검출

Haar cascade의 속도 덕분에 웹캠 실시간 얼굴 검출이 CPU에서 가능합니다. (얼굴 영역에만 GaussianBlur를 하는) ROI 블러 트릭은 간단한 프라이버시/익명화 기법입니다. 프레임 간 얼굴 추적(깜빡임 회피)은 IoU로 검출을 연결하고 칼만 필터로 부드럽게 하세요. cascade만으로는 시간적 연속성이 없습니다.

opencv
import cv2

face_cascade = cv2.CascadeClassifier(
    cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    if not ret:
        break

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.1, 5)

    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
        # blur the face for privacy
        frame[y:y+h, x:x+w] = cv2.GaussianBlur(
            frame[y:y+h, x:x+w], (25, 25), 30)

    cv2.imshow("face", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

측면 / 옆얼굴

Haar cascade는 포즈별입니다. 정면 cascade는 옆얼굴을 놓치므로 profile cascade와 결합하세요. profile cascade가 한쪽으로 학습되었으므로 다른 쪽은 이미지를 수평 반전해 검출하고 결과 좌표를 되돌려 미러링합니다. 이래도 3/4 뷰는 놓칩니다. 현대 검출기(DNN, MTCNN)는 한 모델로 모든 포즈를 처리합니다.

opencv
import cv2

profile_cascade = cv2.CascadeClassifier(
    cv2.data.haarcascades + "haarcascade_profileface.xml")

img = cv2.imread("people.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# detect left-facing profiles
profiles = profile_cascade.detectMultiScale(gray, 1.1, 5)
for (x, y, w, h) in profiles:
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)

# also detect right-facing by flipping the image
flipped = cv2.flip(gray, 1)
profiles_r = profile_cascade.detectMultiScale(flipped, 1.1, 5)
h, w = gray.shape
for (x, y, fw, fh) in profiles_r:
    cv2.rectangle(img, (w - x - fw, y), (w - x, y + fh), (255, 0, 0), 2)

DNN 얼굴 검출

OpenCV의 dnn 모듈은 사전학습 Caffe/TensorFlow/ONNX 모델을 실행할 수 있습니다. SSD와 ResNet 기반 얼굴 검출기는 Haar cascade보다 훨씬 정확하며 한 모델로 모든 포즈를 처리합니다. blobFromImage가 평균 빼기와 스케일링을 한 번에 합니다. 검출은 [0,1]로 정규화되므로 픽셀 박스를 얻으려 (w, h, w, h)를 곱하세요. 모델: SSD(Caffe), YuNet(ONNX, cv.FaceDetectorYN 경유).

opencv
import cv2
import numpy as np

model = cv2.dnn.readNetFromCaffe(
    "deploy.prototxt", "weights.caffemodel")

img = cv2.imread("people.jpg")
h, w = img.shape[:2]

# build a 300x300 blob (mean subtraction + scale)
blob = cv2.dnn.blobFromImage(img, 1.0, (300, 300), (104, 177, 123))

model.setInput(blob)
detections = model.forward()   # shape (1, 1, N, 7)

for i in range(detections.shape[2]):
    conf = detections[0, 0, i, 2]
    if conf > 0.5:
        box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
        x1, y1, x2, y2 = box.astype(int)
        cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
        cv2.putText(img, f"{conf:.2f}", (x1, y1 - 5),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
16

객체 검출

HOG 서술자

HOG(방향 그래디언트 히스토그램)는 엣지 방향의 히스토그램으로 지역 형상을 서술하며 선형 SVM과 결합해 고전적 객체 검출기가 됩니다. 사전학습 사람 검출기는 똑바로 선 전신 보행자에 동작합니다. winStride와 scale가 속도와 재현율을 절충합니다. 현대 딥 검출기(YOLO, SSD)가 훨씬 정확하지만 HOG는 모델 파일 없이 CPU에서 실행됩니다.

opencv
import cv2

img = cv2.imread("person.jpg", cv2.IMREAD_GRAYSCALE)

# create HOG descriptor with the default detector
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

# detectMultiScale returns (rectangles, weights)
boxes, weights = hog.detectMultiScale(
    img, winStride=(8, 8), padding=(4, 4), scale=1.05)

for (x, y, w, h) in boxes:
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)

HOG 피처 시각화

표준 HOG 윈도우는 64x128 픽셀입니다(INRIA 보행자 크기). 파라미터: window(64x128), block(16x16), block stride(8x8), cell(8x8), bins(9). 각 서술자는 3780차원입니다. 커스텀 객체 분류를 위해 많은 양/음 샘플의 HOG 피처를 추출해 선형 SVM(scikit-learn)을 학습한 뒤 setSVMDetector로 검출기를 설정하세요.

opencv
import cv2

img = cv2.imread("person.jpg", cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (64, 128))   # standard HOG window

hog = cv2.HOGDescriptor((64, 128), (16, 16), (8, 8), (8, 8), 9)
descriptor = hog.compute(img)
print(descriptor.shape)   # (3780, 1)

# 9 bins per cell, 7x15 cells, 4 cells per block -> 3780 features
# this is the input vector to a linear SVM classifier

템플릿 매칭

템플릿 매칭은 이미지 위에서 템플릿을 슬라이드하며 유사도 점수를 계산합니다. 회전과 스케일 변화가 없는 정확(또는 거의 정확)한 매칭에만 동작합니다. TM_CCOEFF_NORMED가 가장 견고한 방법이며 결과는 [-1, 1]입니다. 다중 매칭에는 응답 맵에 임계값을 적용하고 겹치는 검출을 피하려 비최대 억제를 적용하세요.

opencv
import cv2
import numpy as np

img = cv2.imread("scene.png", cv2.IMREAD_GRAYSCALE)
template = cv2.imread("template.png", cv2.IMREAD_GRAYSCALE)
h, w = template.shape

# matchTemplate returns a correlation map
res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)

# find the best match
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)

out = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
cv2.rectangle(out, top_left, bottom_right, (0, 255, 0), 2)

# find all matches above a threshold
loc = np.where(res >= 0.8)
for pt in zip(*loc[::-1]):
    cv2.rectangle(out, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 1)

멀티 스케일 템플릿 매칭

멀티 스케일 템플릿 매칭은 스케일 범위를 브루트포스합니다. 느리지만 이미지에서 템플릿 크기를 모를 때 동작합니다. 여전히 회전은 못 다루며, 그러려면 각도까지 훑거나(매우 느림) 피처 매칭을 써야 합니다. 프로덕션 객체 검출에는 템플릿 매칭이 아니라 학습된 검출기(YOLO, SSD)를 쓰세요.

opencv
import cv2
import numpy as np

img = cv2.imread("scene.png", cv2.IMREAD_GRAYSCALE)
template = cv2.imread("template.png", cv2.IMREAD_GRAYSCALE)

best = (-1, None, None)   # (score, location, scale)
for scale in np.linspace(0.5, 1.5, 20):
    resized = cv2.resize(template, None, fx=scale, fy=scale)
    rh, rw = resized.shape
    if rh > img.shape[0] or rw > img.shape[1]:
        continue
    res = cv2.matchTemplate(img, resized, cv2.TM_CCOEFF_NORMED)
    _, max_val, _, max_loc = cv2.minMaxLoc(res)
    if max_val > best[0]:
        best = (max_val, max_loc, scale)

score, (x, y), scale = best
h, w = template.shape
out = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
rw, rh = int(w * scale), int(h * scale)
cv2.rectangle(out, (x, y), (x + rw, y + rh), (0, 255, 0), 2)

DNN 객체 검출 (YOLO)

OpenCV의 dnn 모듈은 내보낸 YOLO/SSD/Faster-RCNN 가중치를 실행할 수 있습니다. 전체 DL 프레임워크를 설치할 수 없을 때 유용합니다. YOLO 출력 파싱은 장황합니다. 각 검출에 중심, 크기, objectness, 클래스별 점수가 있습니다. 겹치는 박스를 하나로 접으려 항상 NMSBoxes(비최대 억제)를 적용하세요. 실시간에는 YOLOv4-tiny를 쓰거나 ONNX + 더 빠른 백엔드로 전환하세요.

opencv
import cv2
import numpy as np

# load a YOLO model (weights + cfg)
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
with open("coco.names") as f:
    classes = [line.strip() for line in f.readlines()]

layer_names = net.getLayerNames()
out_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]

img = cv2.imread("street.jpg")
blob = cv2.dnn.blobFromImage(img, 1/255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
outputs = net.forward(out_layers)

# parse YOLO output: each detection is [cx, cy, w, h, obj, class_scores...]
h, w = img.shape[:2]
boxes, confs, ids = [], [], []
for out in outputs:
    for det in out:
        scores = det[5:]
        cls = int(np.argmax(scores))
        conf = scores[cls]
        if conf > 0.5:
            cx, cy, bw, bh = (det[:4] * [w, h, w, h]).astype(int)
            boxes.append([cx - bw//2, cy - bh//2, bw, bh])
            confs.append(float(conf))
            ids.append(cls)

idxs = cv2.dnn.NMSBoxes(boxes, confs, 0.5, 0.4)   # non-max suppression
17

이미지 세그먼테이션

K-Means 클러스터링

K-means는 색으로 픽셀을 클러스터링합니다. 이미지를 K개 지배 색으로 포스터화하거나 분할하는 간단한 방법입니다. float32 픽셀을 (N, 3)으로 전달하세요(공간 클러스터링에 xy 좌표를 더하면 (N, 5)). K를 올리면 색 분리가 더 세밀해집니다. 공간 응집을 위해서는 각 픽셀에 (x, y) 좌표를, 순수 색 양자화에는 BGR만 쓰세요.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")
h, w = img.shape[:2]

# reshape to a list of pixels (N, 3) in float32
pixels = img.reshape(-1, 3).astype(np.float32)

# kmeans(data, K, criteria, attempts, flags)
K = 4
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0)
_, labels, centers = cv2.kmeans(pixels, K, None, criteria, 10,
                                cv2.KMEANS_RANDOM_CENTERS)

# rebuild the image with cluster centers
centers = np.uint8(centers)
seg = centers[labels.flatten()].reshape((h, w, 3))

GrabCut

GrabCut은 인터랙티브 전경 추출기입니다. 경계 사각형을 주면 가우시안 혼합 모델로 전경/배경을 반복 모델링합니다. 더 세밀한 결과는 픽셀을 수동 레이블(확실한 전경/확실한 배경)한 뒤 GC_INIT_WITH_MASK로 다듬으세요. 비교적 단순한 배경 위의 단일 두드러진 객체에 잘 동작합니다.

opencv
import cv2
import numpy as np

img = cv2.imread("person.jpg")
h, w = img.shape[:2]

# initialize mask (all probable background)
mask = np.zeros((h, w), np.uint8)

# define a rectangle around the foreground object
rect = (50, 50, w - 100, h - 100)

# internal scratch arrays
bgd = np.zeros((1, 65), np.float64)
fgd = np.zeros((1, 65), np.float64)

# run GrabCut: 5 iterations
cv2.grabCut(img, mask, rect, bgd, fgd, 5, cv2.GC_INIT_WITH_RECT)

# mask values: 0=bg, 1=fg, 2=probable bg, 3=probable fg
fg_mask = np.where((mask == 1) | (mask == 3), 255, 0).astype(np.uint8)
result = cv2.bitwise_and(img, img, mask=fg_mask)

Watershed

Watershed는 이미지를 지형도(강도 = 고도)로 취급하고 시드 마커에서 '범람'합니다. 좋은 시드가 없으면 심한 과분할을 만듭니다. 거리 변환 트릭이 (겹친 동전 같은) 접촉 객체의 확실 전경 시드를 만듭니다. 마커: 0=알 수 없음, 1=배경, 2..N=객체, -1=경계. 고전적 '접촉 객체 분리' 파이프라인입니다.

opencv
import cv2
import numpy as np

img = cv2.imread("coins.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold to separate coins from background
_, binary = cv2.threshold(gray, 0, 255,
                          cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# noise removal
kernel = np.ones((3, 3), np.uint8)
opening = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel, iterations=2)

# sure background area
sure_bg = cv2.dilate(opening, kernel, iterations=3)

# sure foreground: distance transform + threshold
dist = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
_, sure_fg = cv2.threshold(dist, 0.5 * dist.max(), 255, 0)
sure_fg = np.uint8(sure_fg)

# unknown region (between sure fg and sure bg)
unknown = cv2.subtract(sure_bg, sure_fg)

# marker labelling
_, markers = cv2.connectedComponents(sure_fg)
markers = markers + 1
markers[unknown == 255] = 0

# watershed modifies markers in place
markers = cv2.watershed(img, markers)
img[markers == -1] = [255, 0, 0]   # boundaries in red

Flood Fill

floodFill은 매직 완드 도구입니다. 시드 픽셀에서 시작해 색이 시드(FIXED_RANGE)나 이전 픽셀의 loDiff/upDiff 이내인 연결된 모든 픽셀을 채웁니다. 마스크는 이미지보다 2픽셀 커야 합니다(양쪽 1픽셀 테두리). 영역 성장, 간단한 배경 교체, 인터랙티브 선택에 유용합니다.

opencv
import cv2

img = cv2.imread("photo.jpg")
h, w = img.shape[:2]
mask = np.zeros((h + 2, w + 2), np.uint8)

# floodFill fills a connected region similar to the seed pixel
# (image, mask, seedPoint, newVal, loDiff, upDiff, flags)
cv2.floodFill(img, mask, (100, 100), (0, 255, 0),
              loDiff=(20, 20, 20), upDiff=(20, 20, 20),
              flags=8 | cv2.FLOODFILL_FIXED_RANGE)

# FLOODFILL_FIXED_RANGE: compare to the seed pixel (strict)
# 4-connectivity (4) or 8-connectivity (8)

# extract the filled mask
filled_mask = mask[1:-1, 1:-1]   # the mask is padded by 1

Connected Components

connectedComponents는 각 흰 영역에 고유 정수를 레이블합니다. 개수, 면적, 무게중심만 필요하면 findContours보다 빠릅니다. connectedComponentsWithStats는 경계 박스와 면적도 반환합니다. 레이블 0은 항상 배경입니다. 기본 연결성은 8(대각 포함)이며 더 엄격하면 connectivity=4를 전달하세요. 입자 세기와 블롭 분석에 쓰세요.

opencv
import cv2
import numpy as np

img = cv2.imread("blobs.png", cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

# connectedComponents returns (num_labels, labels)
num, labels = cv2.connectedComponents(binary)
print(f"found {num - 1} objects (label 0 is background)")

# connectedComponentsWithStats also gives area and bounding box
num, labels, stats, centroids = cv2.connectedComponentsWithStats(binary)
for i in range(1, num):
    x, y, w, h, area = stats[i]
    cx, cy = centroids[i]
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 1)
    cv2.putText(img, str(area), (x, y - 5),
                cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 255), 1)

Mean-Shift / PyrMeanShiftFiltering

pyrMeanShiftFiltering은 모서리를 보존하면서 비슷한 색의 영역을 '평탄화'하는 비모수 세그먼테이션입니다. 컨투어 기반 세그먼테이션 전의 전처리 단계로 자주 쓰입니다. sp(공간 반경)가 알고리즘이 공간적으로 얼마나 보는지, sr(색 반경)이 색 허용 오차를 제어합니다. 값이 클수록 더 크고 부드러운 영역이 만들어집니다.

opencv
import cv2

img = cv2.imread("photo.jpg")

# pyrMeanShiftFiltering: edge-preserving smoothing that homogenizes regions
# (spatialRadius, colorRadius) — larger values merge more
filtered = cv2.pyrMeanShiftFiltering(img, sp=20, sr=40)

# now segment on the filtered image
gray = cv2.cvtColor(filtered, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 0, 255,
                          cv2.THRESH_BINARY + cv2.THRESH_OTSU)

contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)
out = img.copy()
cv2.drawContours(out, contours, -1, (0, 255, 0), 2)
18

카메라 캘리브레이션

체스보드 캘리브레이션

카메라 캘리브레이션은 알려진 패턴(코너를 검출하기 쉬운 체스보드가 표준)의 이미지에서 내재 행렬(초점 거리, 주점)과 렌즈 왜곡 계수를 찾습니다. 다양한 각도의 이미지 약 10~20장이 필요합니다. cornerSubPix가 코너를 서브픽셀 정확도로 다듬으며 좋은 캘리브레이션에 필수입니다. findChessboardCorners에 전달하는 패턴 크기는 내부 코너(사각형-1)입니다.

opencv
import cv2
import numpy as np
import glob

# prepare object points (0,0,0), (1,0,0), ..., for a 7x6 board
objp = np.zeros((6 * 7, 3), np.float32)
objp[:, :2] = np.mgrid[0:7, 0:6].T.reshape(-1, 2)

objpoints = []   # 3-D real-world points
imgpoints = []   # 2-D image points

for fname in glob.glob("calib/*.jpg"):
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # findChessboardCorners returns corners (or None)
    ret, corners = cv2.findChessboardCorners(gray, (7, 6), None)
    if ret:
        # refine to sub-pixel accuracy
        corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1),
            (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001))
        objpoints.append(objp)
        imgpoints.append(corners2)

# calibrate
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(
    objpoints, imgpoints, gray.shape[::-1], None, None)
print("camera matrix:\n", mtx)

이미지 왜곡 제거

undistort는 캘리브레이션 파라미터로 방사 및 접선 렌즈 왜곡을 제거합니다. 비디오에서는 initUndistortRectifyMap으로 맵을 한 번 미리 계산하고 프레임마다 remap을 적용하세요. 반복 undistort 호출보다 훨씬 빠릅니다. alpha=1의 getOptimalNewCameraMatrix는 모든 픽셀을 유지하고(검은 테두리 포함) alpha=0은 유효 영역으로 자릅니다.

opencv
import cv2
import numpy as np

# mtx, dist come from calibrateCamera
img = cv2.imread("distorted.jpg")
h, w = img.shape[:2]

# method 1: simple undistort
undistorted = cv2.undistort(img, mtx, dist)

# method 2: pre-compute the maps for speed (run once, reuse many times)
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(
    mtx, dist, (w, h), 1, (w, h))
mapx, mapy = cv2.initUndistortRectifyMap(
    mtx, dist, None, newcameramtx, (w, h), cv2.CV_16SC2)
undistorted2 = cv2.remap(img, mapx, mapy, cv2.INTER_LINEAR)

# crop to the valid ROI
x, y, rw, rh = roi
undistorted2 = undistorted2[y:y+rh, x:x+rw]

자세 추정 (ArUco)

ArUco 마커는 (QR 코드처럼) 자세 추정용 정사각 피듀셜 마커입니다. 마커의 물리 크기와 카메라 캘리브레이션이 주어지면 카메라 기준의 3차원 회전(rvec)과 이동(tvec)을 얻습니다. opencv-contrib에서 제공됩니다. drawFrameAxes가 마커의 지역 X/Y/Z 축을 그리며 빨강=X, 초록=Y, 파랑=Z, 길이 단위는 미터입니다.

opencv
import cv2

# load a predefined ArUco dictionary
aruco_dict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50)
params = cv2.aruco.DetectorParameters()
detector = cv2.aruco.ArucoDetector(aruco_dict, params)

img = cv2.imread("marker.png")
corners, ids, rejected = detector.detectMarkers(img)

if ids is not None:
    cv2.aruco.drawDetectedMarkers(img, corners, ids)

    # estimate pose (marker size in meters, camera matrix, distortion)
    rvecs, tvecs, _ = cv2.aruco.estimatePoseSingleMarkers(
        corners, 0.05, mtx, dist)
    for rvec, tvec in zip(rvecs, tvecs):
        cv2.drawFrameAxes(img, mtx, dist, rvec, tvec, 0.05)

피듀셜 자세 (SolvePnP)

solvePnP(Perspective-n-Point)는 N개의 3D→2D 대응으로 카메라 자세를 회복합니다. 최소 4점이 필요합니다. 정확도에는 SOLVEPNP_ITERATIVE(기본), 평면 타깃에는 SOLVEPNP_IPPE를 쓰세요. rvec은 회전 벡터(축 × 각도)이며 3x3 행렬 변환에는 Rodrigues를 쓰세요. 마커 기반 AR과 6자유도 추적의 기초입니다.

opencv
import cv2
import numpy as np

# 3-D coordinates of known object points (e.g. a cube corner)
obj_points = np.array([
    [0, 0,  0], [1, 0,  0], [1, 1,  0], [0, 1,  0],
    [0, 0, -1], [1, 0, -1], [1, 1, -1], [0, 1, -1],
], dtype=np.float32)

# corresponding 2-D image points (detected via feature matching etc.)
img_points = np.array([
    [120, 90], [220, 88], [225, 190], [115, 195],
    [80, 60],  [240, 55], [248, 210], [70, 215],
], dtype=np.float32)

# solvePnP(objectPoints, imagePoints, cameraMatrix, distCoeffs)
ret, rvec, tvec = cv2.solvePnP(obj_points, img_points, mtx, dist)
print("rotation:", rvec.ravel())
print("translation:", tvec.ravel())

# project the 3-D points back to verify
proj, _ = cv2.projectPoints(obj_points, rvec, tvec, mtx, dist)

재투영 오차

재투영 오차가 캘리브레이션 품질의 금융 표준입니다. 투영된 3D 점이 검출된 2D 점에서 얼마나 벗어나는지 측정합니다. 좋은 캘리브레이션은 평균 0.5px 미만이고, 1px 초과는 보통 나쁜 이미지 집합, 잘못된 패턴 크기, 움직임 흐림을 의미합니다. 이미지별 오차로 나쁜 캘리브레이션 이미지를 찾아 버리세요.

opencv
import cv2
import numpy as np

# after calibrateCamera or solvePnP, check accuracy
mean_err = 0
total = 0
for i in range(len(objpoints)):
    # project the 3-D points using the estimated pose
    proj, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist)
    err = cv2.norm(imgpoints[i], proj, cv2.NORM_L2) / len(proj)
    mean_err += err
    total += 1

print(f"mean reprojection error: {mean_err / total:.3f} px")
# good calibrations are typically < 0.5 px per corner
19

깊이와 스테레오

스테레오 시차 맵

StereoBM은 정합된 스테레오 쌍의 시차 맵(좌/우 픽셀 오프셋)을 계산하며 가까운 객체일수록 시차가 큽니다. numDisparities는 16의 배수, blockSize는 홀수여야 합니다. 출력은 16배 스케일된 int16이므로 픽셀 시차로는 16.0으로 나누세요. StereoSGBM(반전역 블록 매칭)은 느리지만 훨씬 정확합니다.

opencv
import cv2

# stereo pair (rectified: corresponding points on the same row)
imgL = cv2.imread("left.png", cv2.IMREAD_GRAYSCALE)
imgR = cv2.imread("right.png", cv2.IMREAD_GRAYSCALE)

# StereoBM (block matching, fast)
stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)
disparity = stereo.compute(imgL, imgR)

# normalize for display
disp_vis = cv2.normalize(disparity, None, 0, 255,
                         cv2.NORM_MINMAX, cv2.CV_8U)

StereoSGBM

StereoSGBM은 주사선에 걸친 평활성을 강제합니다(반전역 매칭). StereoBM보다 훨씬 정확하지만 런타임 약 5배 비용이 듭니다. P1/P2가 각각 1과 1 초과의 시차 변화에 벌점을 두며, 경험칙은 P1=8*C*blockSize², P2=32*C*blockSize²입니다(C는 채널 수). speckle* 파라미터가 작은 노이즈 시차 영역을 필터합니다.

opencv
import cv2

imgL = cv2.imread("left.png", cv2.IMREAD_GRAYSCALE)
imgR = cv2.imread("right.png", cv2.IMREAD_GRAYSCALE)

sgbm = cv2.StereoSGBM_create(
    minDisparity=0,
    numDisparities=128,
    blockSize=5,
    P1=8 * 3 * 5 * 5,
    P2=32 * 3 * 5 * 5,
    disp12MaxDiff=1,
    uniquenessRatio=10,
    speckleWindowSize=100,
    speckleRange=32,
)

disparity = sgbm.compute(imgL, imgR)
disp_vis = cv2.normalize(disparity, None, 0, 255,
                         cv2.NORM_MINMAX, cv2.CV_8U)

스테레오 캘리브레이션과 정합

스테레오 매칭에는 이미지가 정합되어야 합니다. 에피폴라 선이 수평으로 정렬되어 대응 점이 같은 행을 공유합니다. 파이프라인: 각 카메라 캘리브레이션 → 둘 사이의 R과 T를 찾는 스테레오 캘리브레이션 → 정합 변환을 계산하는 stereoRectify → 프레임마다 한 번 remap. 정합 후 시차 계산은 행을 따라 1차원 탐색입니다.

opencv
import cv2
import numpy as np

# calibrate each camera separately, then stereo-calibrate
ret, mtxL, distL, rvecsL, tvecsL = cv2.calibrateCamera(
    objpoints, imgpointsL, grayL.shape[::-1], None, None)
ret, mtxR, distR, rvecsR, tvecsR = cv2.calibrateCamera(
    objpoints, imgpointsR, grayR.shape[::-1], None, None)

# stereo calibration: finds the rigid transform between cameras
flags = cv2.CALIB_FIX_INTRINSIC
ret, mtxL, distL, mtxR, distR, R, T, E, F = cv2.stereoCalibrate(
    objpoints, imgpointsL, imgpointsR, mtxL, distL, mtxR, distR,
    grayL.shape[::-1], flags=flags)

# stereo rectification: aligns epipolar lines to be horizontal
R1, R2, P1, P2, Q, _, _ = cv2.stereoRectify(
    mtxL, distL, mtxR, distR, grayL.shape[::-1], R, T)

# pre-compute the rectification maps
mapL1, mapL2 = cv2.initUndistortRectifyMap(
    mtxL, distL, R1, P1, grayL.shape[::-1], cv2.CV_16SC2)
mapR1, mapR2 = cv2.initUndistortRectifyMap(
    mtxR, distR, R2, P2, grayR.shape[::-1], cv2.CV_16SC2)

rectL = cv2.remap(imgL, mapL1, mapL2, cv2.INTER_LINEAR)
rectR = cv2.remap(imgR, mapR1, mapR2, cv2.INTER_LINEAR)

시차로부터의 깊이

깊이는 시차에 반비례합니다. depth = focal × baseline / disparity. 기준선(카메라 간격)과 초점 거리는 일관된 단위여야 합니다(보통 초점은 픽셀, 기준선은 미터이면 깊이는 미터). 멀리 있는 객체는 시차가 노이즈합니다(작은 시차, 큰 깊이 오차). 그래서 원거리 스테레오 카메라는 넓은 기준선이 필요합니다.

opencv
import cv2
import numpy as np

# given a disparity map and the stereo baseline + focal length:
# depth = (focal_length * baseline) / disparity

focal = 700.0       # pixels (from camera matrix)
baseline = 0.1      # meters (distance between cameras)

disparity = sgbm.compute(rectL, rectR).astype(np.float32) / 16.0

# avoid division by zero
disparity[disparity <= 0] = 0.1
depth = (focal * baseline) / disparity   # in meters

# cap to a sensible range
depth = np.clip(depth, 0.1, 100.0)
depth_vis = cv2.normalize(depth, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)

광학 흐름 (Lucas-Kanade)

Lucas-Kanade는 희소 광학 흐름을 계산하며 작은 지역 움직임을 가정하고 키포인트 집합을 프레임 간 추적합니다. 중간 정도의 움직임에는 빠르고 정확하며, 크거나 빠른 움직임에는 실패합니다(피라미드 사용. calcOpticalFlowPyrLK가 이미 그렇게 함). status==1은 점이 성공적으로 추적됐음을 뜻합니다. 픽셀별 밀집 흐름에는 calcOpticalFlowFarneback을 쓰세요. 훨씬 느리지만 전체 움직임 필드를 만듭니다.

opencv
import cv2
import numpy as np

cap = cv2.VideoCapture("traffic.mp4")
ret, prev = cap.read()
prev_gray = cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY)

# detect good features to track
prev_pts = cv2.goodFeaturesToTrack(prev_gray, 100, 0.3, 7)

while True:
    ret, frame = cap.read()
    if not ret:
        break
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # sparse optical flow (Lucas-Kanade)
    next_pts, status, err = cv2.calcOpticalFlowPyrLK(
        prev_gray, gray, prev_pts, None)

    good_new = next_pts[status == 1]
    good_old = prev_pts[status == 1]

    for new, old in zip(good_new, good_old):
        a, b = new.ravel()
        c, d = old.ravel()
        cv2.line(frame, (int(a), int(b)), (int(c), int(d)), (0, 255, 0), 2)
        cv2.circle(frame, (int(a), int(b)), 3, (0, 0, 255), -1)

    cv2.imshow("flow", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    prev_gray = gray.copy()
    prev_pts = good_new.reshape(-1, 1, 2)

cap.release()
20

유틸리티와 팁

성능 측정

OpenCV 호출 벤치마크에는 TickMeter가 가장 깔끔합니다. getTimeMilli가 실시간 밀리초를 반환합니다. getTickCount/getTickFrequency가 사이클 정확 타이밍을 줍니다. 지터를 상쇄하려 항상 여러 반복의 평균을 내고, 벤치마크 시에는 cv2.imshow를 끄세요(GUI 렌더링이 지배). setNumThreads가 기저 병렬 백엔드(TBB/OpenMP)를 제어합니다.

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")

# TickMeter: high-precision timer
tm = cv2.TickMeter()
tm.start()
for _ in range(100):
    blurred = cv2.GaussianBlur(img, (5, 5), 0)
tm.stop()
print(f"avg: {tm.getTimeMilli() / 100:.3f} ms")

# getTickCount / getTickFrequency
t0 = cv2.getTickCount()
edges = cv2.Canny(img, 50, 150)
t1 = cv2.getTickCount()
print(f"Canny: {(t1 - t0) / cv2.getTickFrequency() * 1000:.2f} ms")

# set USE_AVX / thread count
cv2.setNumThreads(4)
print(cv2.getNumThreads())

마우스 이벤트

setMouseCallback이 명명된 윈도우의 마우스 이벤트 핸들러를 등록합니다. 인터랙티브 ROI 선택, 주석 도구, 간단한 그림 앱에 유용합니다. 흔한 이벤트: LBUTTONDOWN, LBUTTONUP, MOUSEMOVE, RBUTTONDOWN. 핸들러는 최상위(또는 전역) 함수여야 하며, 콜백 시그니처가 고정이라 상태 공유는 전역이 표준입니다.

opencv
import cv2
import numpy as np

drawing = False
ix, iy = -1, -1

def on_mouse(event, x, y, flags, param):
    global drawing, ix, iy
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y
    elif event == cv2.EVENT_MOUSEMOVE and drawing:
        cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), -1)
    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), -1)

img = np.zeros((512, 512, 3), np.uint8)
cv2.namedWindow("canvas")
cv2.setMouseCallback("canvas", on_mouse)

while True:
    cv2.imshow("canvas", img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cv2.destroyAllWindows()

Trackbar

Trackbar는 스크립트를 재시작하지 않고 파라미터를 인터랙티브 튜닝하게 합니다. 좋은 임계값, 커널 크기, HSV 범위 찾기에 귀중합니다. 콜백은 변화마다 호출되며(메인 루프에서 getTrackbarPos를 폴링하면 no-op으로 충분) 명명된 윈도우 위에 만들고 getTrackbarPos(window, name)로 읽어야 합니다.

opencv
import cv2
import numpy as np

def nothing(x):
    pass

img = np.zeros((300, 512, 3), np.uint8)
cv2.namedWindow("image")

# create trackbars
cv2.createTrackbar("R", "image", 0, 255, nothing)
cv2.createTrackbar("G", "image", 0, 255, nothing)
cv2.createTrackbar("B", "image", 0, 255, nothing)
cv2.createTrackbar("switch", "image", 0, 1, nothing)

while True:
    cv2.imshow("image", img)
    if cv2.waitKey(1) & 0xFF == 27:    # Esc to quit
        break

    r = cv2.getTrackbarPos("R", "image")
    g = cv2.getTrackbarPos("G", "image")
    b = cv2.getTrackbarPos("B", "image")
    s = cv2.getTrackbarPos("switch", "image")

    if s == 0:
        img[:] = 0
    else:
        img[:] = [b, g, r]

cv2.destroyAllWindows()

ROI 선택기

selectROI는 사용자가 사각형을 드래그하고 Enter/Space를 누르는 인터랙티브 윈도우를 열며 직접 마우스 콜백을 쓰는 것보다 훨씬 쉽습니다. 취소는 'c'(모두 0 반환). selectROIs로 여러 사각형을 차례로 고를 수 있습니다. 반환 튜플은 (x, y, w, h)이며 img[y:y+h, x:x+w]로 잘라내세요.

opencv
import cv2

img = cv2.imread("photo.jpg")

# built-in ROI selector (drag a rectangle)
roi = cv2.selectROI("select", img, showCrosshair=True, fromCenter=False)
cv2.destroyAllWindows()

x, y, w, h = roi
cropped = img[y:y+h, x:x+w]

# multiple ROIs
rois = cv2.selectROIs("select", img, showCrosshair=True, fromCenter=False)
for r in rois:
    x, y, w, h = r
    cv2.imshow("roi", img[y:y+h, x:x+w])
    cv2.waitKey(0)
cv2.destroyAllWindows()

흔한 함정

이 다섯 가지 함정이 OpenCV 버그의 대부분을 만듭니다. BGR/RGB 혼동(빨강과 파랑 교체), uint8 오버플로(어두움/밝은 아티팩트), 좌표 순서(1픽셀 어긋난 ROI), 파일 누락 None(이후 연산이 암호 같은 오류로 크래시), waitKey 잊기(윈도우가 갱신 안 됨). 일찍 내재화하세요. 모든 OpenCV 개발자가 각각 최소 한 번씩 겪습니다.

opencv
import cv2
import numpy as np

# 1. BGR vs RGB — imshow expects BGR; matplotlib expects RGB
img = cv2.imread("p.jpg")
# plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))   # correct
# plt.imshow(img)                                     # colors look wrong

# 2. uint8 overflow — use cv2 ops or upcast
a = np.array([200], np.uint8)
print(a + 100)        # [44]   (wraps, WRONG)
print(cv2.add(a, 100))  # [[255]] (saturates, RIGHT)

# 3. (x, y) vs (row, col) — drawing uses (x,y), NumPy uses [y,x]
cv2.rectangle(img, (10, 20), (110, 120), (0, 255, 0), 2)  # x=10..110
roi = img[20:120, 10:110]   # rows 20..120, cols 10..110 (same region)

# 4. None returned by imread when the file is missing
img = cv2.imread("missing.jpg")
if img is None:
    raise FileNotFoundError("could not read image")

# 5. waitKey is mandatory for imshow to actually render
cv2.imshow("img", img)
cv2.waitKey(1)   # without this, the window may stay blank

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.