pytorch

[pytorch] Sobel Filtering

Leetora 2023. 11. 27. 13:40

☑️Sobel Filtering

  • CNN 커널에 해당하는 것으로, 이미지 특성을 추출하기 위한 행렬을 의미
  • Sobel Filter는 X 필터와, Y 필터 2종류
  • 각 축에 따른 유사도를 갖고 있음
  • 3X3 행렬 모습을 갖고 있으며, 원소는 (2, 1, 0, -1, -2)로 구성
  • 좌우대칭(x filter) 또는 상하대칭(y filter)의 모습을 가짐

❓동작 원리

  1. window에 따라 correlations 값이 달라짐
    • 큰 값이 나올 수도, 작은 음수 값이 나올 수도, 0이 나올 수도 있음
  2. 각각의 correlation 값을 보면, filter의 모양과 window의 모양이 비슷할 때 큰 값을 출력
    • 반대의 특성을 지니면 작은 음수, 자신과 상관없는 부분이면 0 출력
    • Sobel Filter는 2차원 Correlation 연산을 수행함
    • 2D Correlation 연산: 원소끼리 곱한 후 더해주는 것 - 즉, pixel과 filter의 dot(내적)

✍🏻X filter

import numpy as np
import matplotlib.pyplot as plt 

#x필터와 y필터를 생성
x_filter = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) 
y_filter = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) 

#white&black patch를 설정
white_patch = 255*np.ones(shape=(10,10)) 
black_patch = 0*np.ones(shape=(10, 10)) 

#img를 생성해 타일 한 줄을 생성
img1 = np.hstack([white_patch, black_patch])
img2 = np.hstack([black_patch, white_patch])

#전체를 반복하는 tile을 생성
img = np.tile(np.vstack([img1, img2]), reps=([2, 2])) 

#height / width의 window 개수를 구하기
H = len(img) #40 
W = len(img[0]) #40


F = len(x_filter) #3
H_ = H - F + 1 #38
W_ = W - F + 1 #38

#H의 window개수 / W의 window 개수만큼 0을 가즌ㄴ 배열 생성
result_x = np.zeros([H_, W_]) 
result_y = np.zeros([H_, W_]) 


for H_idx in range(H_): 
	for W_idx in range(W_): 
		window = img[H_idx:H_idx+F, W_idx:W_idx+F] 
		result_x[H_idx, W_idx] = np.sum(window*x_filter)
		result_y[H_idx, W_idx] = np.sum(window*y_filter) 

fig, ax = plt.subplots(figsize=(5, 5)) 
ax.imshow(img, cmap='gray') 
ax.imshow(result_x, cmap='gray') 
ax.imshow(result_y, cmap='gray') 
ax.tick_params(left=False, labelleft=False, bottom=False, labelbottom=False)

 

✍🏻Y filter

import numpy as np 
import matplotlib.pyplot as plt 

x_filter = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) 
y_filter = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) 

white_patch = 255*np.ones(shape=(10, 10)) 
black_patch = 0*np.ones(shape=(10, 10)) 

img1 = np.hstack([white_patch, black_patch])
img2 = np.hstack([black_patch, white_patch]) 
img = np.tile(np.vstack([img1, img2]), reps=([2, 2])) 

H = len(img) #40 
W = len(img[0]) #40 
F = len(x_filter) #3 

H_ = H - F + 1 #38 
W_ = W - F + 1 #38 
result_x = np.zeros([H_, W_]) 
result_y = np.zeros([H_, W_]) 

for H_idx in range(H_): 
	for W_idx in range(W_): 
		window = img[H_idx:H_idx+F, W_idx:W_idx+F] 
		result_x[H_idx, W_idx] = np.sum(window*x_filter)
		result_y[H_idx, W_idx] = np.sum(window*y_filter)

print(result_x)
print(result_x, '\n')
print(len(result_x))
print(result_y, '\n')
print(len(result_y)) 

fig, ax = plt.subplots(figsize=(5, 5)) 

ax.imshow(img, cmap='gray')
ax.imshow(result_x, cmap='gray')
ax.imshow(result_y, cmap='gray')
ax.tick_params(left=False, labelleft=False, bottom=False, labelbottom=False)