Canny 엣지 검출과 최소자승법을 활용한 동심원 반경 정밀 추출

문제 정의 및 핵심 난제

안구 이미지 처리 또는 특정 동심원 패턴 분석 시, 내부에서 외부로 두 번째 원형 객체의 외곽선(타겟 엣지)을 정밀하게 추출해야 하는 경우가 있습니다. 이 과정에서 두 가지 주요 난제가 발생합니다.

  • 노이즈 간섭: 속눈썹이나 주변 털로 인한 엣지 끊김 및 위양성(False Positive) 발생.
  • 초정밀도 요구: 서브픽셀(Sub-pixel) 수준인 0.1 픽셀 오차 이내의 반경 계산 필요.

1단계: Canny 엣지 검출 및 초기 중심점 추정

먼저 Canny 알고리즘을 적용하여 엣지를 추출하고, 계층적 윤곽선 분석을 통해 가장 안쪽의 유효한 윤곽선을 찾아 초기 중심점을 산출합니다.

import cv2
import numpy as np

def estimate_initial_center(image_path, low_thresh, high_thresh):
    src_img = cv2.imread(image_path, cv2.IMREAD_COLOR)
    gray_img = cv2.cvtColor(src_img, cv2.COLOR_BGR2GRAY)
    
    # Canny 엣지 검출 및 관심 영역(ROI) 크롭
    raw_edges = cv2.Canny(gray_img, low_thresh, high_thresh, apertureSize=3, L2gradient=True)
    cropped_edges = crop_center_roi(raw_edges)
    
    # 윤곽선 및 계층 구조 추출
    contours, hierarchy = cv2.findContours(cropped_edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    
    target_cnt = None
    min_cnt_length = float('inf')
    
    for idx, cnt in enumerate(contours):
        # 최상위 윤곽선(부모 없음) 제외 및 노이즈 필터링
        if hierarchy[0][idx][3] == -1 or len(cnt) < 50:
            continue
        if len(cnt) < min_cnt_length:
            min_cnt_length = len(cnt)
            target_cnt = cnt
            
    # 바운딩 박스 기반 중심점 산출
    x_vals = target_cnt[:, 0, 0]
    y_vals = target_cnt[:, 0, 1]
    center_x = int((np.min(x_vals) + np.max(x_vals)) / 2)
    center_y = int((np.min(y_vals) + np.max(y_vals)) / 2)
    
    return src_img, cropped_edges, (center_x, center_y)

cv2.RETR_TREE 옵션을 사용하면 윤곽선의 포함 관계를 파악할 수 있어 외부 노이즈를 효과적으로 걸러낼 수 있습니다. 길이가 짧은 윤곽선을 제외하고 가장 안쪽에 위치한 윤곽선을 선택하여 중심점을 계산합니다.

2단계: 방사형 레이캐스팅을 통한 타겟 엣지 추출

중심점에서 외부로 뻗어나가는 8방향의 가상 레이(Ray)를 생성하여, 안쪽부터 네 번째에 해당하는 엣지 교차점을 찾습니다. 이후 연결 요소(Connected Components) 분석을 통해 해당 교차점들을 가장 많이 포함하는 곡선을 타겟 엣지로 확정합니다.

def extract_target_boundary(edges, center_point, target_idx=3):
    cx, cy = center_point
    radial_rays = generate_radial_lines(cx, cy, num_rays=8)
    
    intersection_candidates = []
    for ray in radial_rays:
        hits = calculate_ray_intersections(edges, ray)
        if len(hits) > target_idx:
            intersection_candidates.append(hits[target_idx])
            
    # 연결 요소(Connected Components) 분석
    num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(edges)
    
    # 후보 교차점들을 가장 많이 포함하는 레이블 식별
    dominant_label = find_most_frequent_label(labels, intersection_candidates)
    
    # 해당 레이블의 전체 좌표 추출
    target_pixels = np.column_stack(np.where(labels == dominant_label))
    return target_pixels

이 단계를 거치면 속눈썹에 의해 가려지지 않은 주요 구간들의 좌표가 추출됩니다. 그러나 노이즈로 인해 여전히 일부 구간이 누락될 수 있으므로 추가적인 보정이 필요합니다.

3단계: 최소자승법 및 이상치 제거를 통한 정밀 원 피팅

추출된 불완전한 곡선을 바탕으로 최소자승법(Least Squares Method)을 적용하여 초기 원의 반경과 중심을 추정합니다. 그 후, 추정된 원과 거리가 가까운 인접 연결 요소들을 병합하고, 반복적인 이상치(Outlier) 제거를 통해 0.1 픽셀 수준의 정밀도를 달성합니다.

def refine_circle_fit(target_pixels, all_labels, initial_center, max_iters=10):
    # 초기 최소자승법 원 피팅
    est_radius, est_center = fit_circle_least_squares(target_pixels)
    cx, cy = est_center
    
    # 기하학적 거리가 가까운 인접 컴포넌트 좌표 병합
    adjacent_pixels = get_closest_components(all_labels, cx, cy, dist_threshold=5.0)
    if adjacent_pixels is not None:
        target_pixels = np.vstack([target_pixels, adjacent_pixels])
        
    # 반복적 이상치 필터링
    for _ in range(max_iters):
        target_pixels, current_std = remove_outliers(target_pixels, cx, cy, 
                                                     dist_thresh=2.0, std_thresh=0.4)
        if current_std < 0.4:
            break
            
    # 최종 정밀 피팅
    final_radius, final_center = fit_circle_least_squares(target_pixels)
    return final_radius, final_center

이러한 다단계 필터링과 피팅 과정을 거치면, 속눈썹 등의 가림(Occlusion) 현상이 있더라도 수학적으로 가장 타당한 원형 경로를 복원할 수 있으며, 요구되는 서브픽셀 정밀도를 충족하는 반경 값을 도출할 수 있습니다.

태그: OpenCV Canny python LeastSquares ImageProcessing

10월 29일 02:05에 게시됨