Skip to content

Mean shift

Mean shift is a non-parametric feature-space analysis technique for locating the maxima of a density function, a so-called mode-seeking algorithm. Application domains include cluster analysis in computer vision and image processing.

Mean shift filter

Implementation

import numpy as np
from scipy.ndimage import label, generate_binary_structure

# 이미지를 불러옵니다. (예: grayscale 이미지)
image = cv2.imread('input_image.jpg', 0)

# 필터 윈도우 크기를 정의합니다.
window_size = 5

# 필터링된 이미지를 저장할 배열을 생성합니다.
filtered_image = np.zeros_like(image, dtype=np.uint8)

# 이미지 크기를 가져옵니다.
height, width = image.shape

# Mean Shift 필터 함수를 정의합니다.
def mean_shift_filter(image, window_size, threshold):
    half_size = window_size // 2

    for y in range(half_size, height - half_size):
        for x in range(half_size, width - half_size):
            window = image[y - half_size:y + half_size + 1, x - half_size:x + half_size + 1]
            window_mean = np.mean(window)
            mask = (window >= window_mean - threshold) & (window <= window_mean + threshold)
            filtered_image[y, x] = np.mean(window[mask])

# Mean Shift 필터를 적용합니다.
mean_shift_filter(image, window_size, threshold=10)

# 결과 이미지를 저장하거나 표시합니다.
cv2.imwrite('output_image.jpg', filtered_image)
cv2.imshow('Mean Shift Filtered Image', filtered_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

See also

Favorite site