소스 뷰어
import cv2, numpy as np, matplotlib.pyplot as plt
# 이미지 불러오기 (흑백 이미지로 변환)
image = cv2.imread('example.jpg', cv2.IMREAD_GRAYSCALE)
# 수평 방향 (x 방향) 마스크
Gx = np.array([[-1, -1, -1],
[0, 0, 0],
[1, 1, 1]])
# 수직 방향 (y 방향) 마스크
Gy = np.array([[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1]])
# 마스크를 이용해 이미지 필터링 (convolution)
edge_x = cv2.filter2D(image, -1, Gx) # x 방향 에지
edge_y = cv2.filter2D(image, -1, Gy) # y 방향 에지
# 두 방향의 에지를 합성하여 최종 에지 검출
edges_combined = cv2.addWeighted(edge_x, 0.5, edge_y, 0.5, 0)
# 폰트 사이즈
fs = font_size = 30
# 결과 출력
plt.figure(figsize=(16, 16))
plt.subplot(2, 2, 1)
plt.title("Original Image", fontsize=fs)
plt.imshow(image, cmap='gray')
plt.axis('off')
plt.subplot(2, 2, 2)
plt.title("Prewitt Edge X (Gx)", fontsize=fs)
plt.imshow(edge_x, cmap='gray')
plt.axis('off')
plt.subplot(2, 2, 3)
plt.title("Prewitt Edge Y (Gy)", fontsize=fs)
plt.imshow(edge_y, cmap='gray')
plt.axis('off')
plt.subplot(2, 2, 4)
plt.title("Combined Prewitt Edges (Gx + Gy)", fontsize=fs)
plt.imshow(edges_combined, cmap='gray')
plt.axis('off')
plt.tight_layout()
plt.show()