수학적 영상처리

[파이썬] Notch Filtering 으로 모아레 패턴 제거하기

제갈티 2024. 9. 12. 09:03

노치 필터링으로 제거된 이미지속 줄무늬

- 노치 필터는 대역필터(Band Pass Filter) 중에서 스펙트럼 대역폭이 매우 좁은 특수한 필터를 말합니다.

- 1차원 신호에서와 마찬가지로 이미지와 같은 2차원 신호에서도 마찬가지로 노치필터링은 가능한데요..

- 그림과 같이 수직이나 수평방향 줄무늬 노이즈(아마도 저주파 교류전원에 의한 간섭? 형광등 주파수와의 교란??) 를 제거하는데 종종 쓰입니다. 당근, 경사진 방향의 줄무늬 필터링도 가능하구요.

- 처리 절차는 대충 이러합니다:  왜곡된 이미지 입력> 2차원 푸리에변환 > 진폭 스펙트럼 > 줄무늬에 해당하는 공간주파수 제거 > 푸리;에 역변환 > 필터링된 이미지.


import cv2
import numpy as np
import tkinter as tk
from PIL import Image, ImageTk

def notch_filter(img, d0=9, u_k=0, v_k=0):
    f = np.fft.fft2(img)
    fshift = np.fft.fftshift(f)
    
    rows, cols = img.shape
    crow, ccol = rows//2, cols//2
    
    mask = np.ones((rows, cols), np.uint8)
    for d in range(d0):
        mask[crow+v_k-d:crow+v_k+d+1, ccol+u_k] = 0
        mask[crow-v_k-d:crow-v_k+d+1, ccol-u_k] = 0
        
    fshift_filtered = fshift * mask
    
    f_ishift = np.fft.ifftshift(fshift_filtered)
    img_back = np.fft.ifft2(f_ishift)
    img_back = np.real(img_back)
    
    return fshift_filtered, img_back

- 이미지에 대한 노치 필터를 정의 합니다.

- 여기선 노치필터링 마스크로 단순 Ideal Filter(=0)를 사용합니다.

def display_images(input_img, spectrum_img, filtered_spectrum, filtered_img):
    root = tk.Tk()
    root.title("Notch Filtering")

    input_img_tk = ImageTk.PhotoImage(Image.fromarray(input_img))
    spectrum_img_tk = ImageTk.PhotoImage(Image.fromarray(spectrum_img))
    filtered_spectrum_tk = ImageTk.PhotoImage(Image.fromarray(filtered_spectrum))
    filtered_img_tk = ImageTk.PhotoImage(Image.fromarray(filtered_img))

    input_label = tk.Label(root, image=input_img_tk)
    input_label.grid(row=0, column=0)

    spectrum_label = tk.Label(root, image=spectrum_img_tk)
    spectrum_label.grid(row=0, column=1)

    filtered_spectrum_label = tk.Label(root, image=filtered_spectrum_tk)
    filtered_spectrum_label.grid(row=1, column=0)

    filtered_label = tk.Label(root, image=filtered_img_tk)
    filtered_label.grid(row=1, column=1)

    root.mainloop()

- 디스플레이 함수 정의

if __name__ == "__main__":
    img = cv2.imread('/Users/sgi/Desktop/depthcam.png', 0)
    
    rows, cols = img.shape
    fshift_filtered, filtered_img = notch_filter(img, d0=8, u_k=0, v_k=9)
    
    f = np.fft.fft2(img)
    fshift = np.fft.fftshift(f)
    magnitude_spectrum = 20*np.log(np.abs(fshift))
    filtered_spectrum = 20*np.log(np.abs(fshift_filtered))
    
    display_images(img, magnitude_spectrum, filtered_spectrum, filtered_img)
    
    cv2.imwrite('filtered_output.jpg', filtered_img)

- 메인 루틴을 기술합니다.

참고: 

푸리에 영상처리: https://www.aladin.co.kr/shop/wproduct.aspx?ItemId=309060931

 

딥러닝을 위한 푸리에 영상처리

푸리에 변환(Fourier Transform)은 오디오 신호처리는 물론이고 이미지나 비디오 같은 영상신호처리, 그리고 딥러닝 분야에서도 그 성능이나 강건함에 있어서 많은 가능성을 가지고 있다. 푸리에 변

www.aladin.co.kr