[파이썬] opencv-python 이미지의 색상 히스토그램 일치
이미지 처리에서 색상 히스토그램 일치는 이미지의 색상 분포를 조정하여 다른 이미지와 색상을 일치시키는 기술입니다. OpenCV-Python을 사용하면 간단하게 이미지의 색상 히스토그램을 분석하고 조정할 수 있습니다.
색상 히스토그램이란?
색상 히스토그램은 주어진 이미지에서 각 색상의 분포를 표시하는 그래프입니다. X축은 색상 값의 범위를 나타내고, Y축은 해당 색상 값의 빈도를 나타냅니다. 이를 통해 이미지의 색상 분포를 시각화할 수 있습니다.
색상 히스토그램 일치의 필요성
색상 히스토그램 일치는 이미지 간의 색상 차이를 줄여주어, 이미지의 비슷한 색조와 채도를 갖도록 만들어줍니다. 이는 이미지 분석, 객체 검출, 영상 처리 등 다양한 컴퓨터 비전 작업에 중요한 전처리 과정입니다.
OpenCV-Python을 이용한 색상 히스토그램 일치
OpenCV-Python을 사용하여 이미지의 색상 히스토그램 일치를 수행하는 방법을 알아보겠습니다. 아래는 간단한 예제 코드입니다.
import cv2
import numpy as np
import matplotlib.pyplot as plt
def match_histograms(source, target):
# 원본 이미지와 타겟 이미지의 히스토그램 계산
source_hist = cv2.calcHist([source], [0, 1], None, [180, 256], [0, 180, 0, 256])
target_hist = cv2.calcHist([target], [0, 1], None, [180, 256], [0, 180, 0, 256])
# 모든 픽셀의 누적 히스토그램 계산
source_hist_cumulative = source_hist.cumsum()
target_hist_cumulative = target_hist.cumsum()
# 누적 히스토그램의 정규화
source_hist_cumulative_normalized = source_hist_cumulative / source_hist_cumulative.max()
target_hist_cumulative_normalized = target_hist_cumulative / target_hist_cumulative.max()
# 히스토그램 일치 함수 적용
lut = np.interp(source_hist_cumulative_normalized, target_hist_cumulative_normalized, np.arange(256))
matched = cv2.LUT(source, lut)
return matched
# 원본 이미지와 대상 이미지 읽기
source_image = cv2.imread('source.jpg')
target_image = cv2.imread('target.jpg')
# 색상 히스토그램 일치 수행
matched_image = match_histograms(source_image, target_image)
# 결과 이미지 출력
plt.subplot(131), plt.title('Source'), plt.imshow(cv2.cvtColor(source_image, cv2.COLOR_BGR2RGB))
plt.subplot(132), plt.title('Target'), plt.imshow(cv2.cvtColor(target_image, cv2.COLOR_BGR2RGB))
plt.subplot(133), plt.title('Matched'), plt.imshow(cv2.cvtColor(matched_image, cv2.COLOR_BGR2RGB))
plt.show()
위 코드는 두 개의 이미지(source.jpg와 target.jpg)에서 원본 이미지의 색상 히스토그램을 대상 이미지의 색상 히스토그램에 일치시키는 함수를 구현한 예제입니다. 매칭된 이미지를 Matplotlib을 통해 출력합니다.
결론
OpenCV-Python을 사용하여 이미지의 색상 히스토그램 일치를 적용하는 방법에 대해 알아보았습니다. 색상 히스토그램 일치는 이미지 분석 및 처리 작업에서 매우 유용한 기술로, 다양한 컴퓨터 비전 프로젝트에서 활용할 수 있습니다.