경계선 검출(Edge Detection)은 이미지에서 물체의 윤곽선을 찾아내는 방법입니다. 밝기 변화를 이용하기 때문에 이미지를 grayscale로 변환 후에 윤곽선을 찾아내게 됩니다.
이번시간엔 대표적인 에지 검출 알고리즘 Canny Edge Detection에 대해 소개하도록 하겠습니다.
Canndy Edge Detection은 이미지의 노이즈 제거 후 경계선을 찾아내는 알고리즘입니다.
threshold1과 threshod2를 사용하며 그 값에 따라 검출된 경계선의 민감도가 달라집니다.
import cv2
import matplotlib.pyplot as plt
# 1. 이미지 읽기
img = cv2.imread('Summer_Lab_in_No_Aircon.png', cv2.IMREAD_COLOR)
if img is None:
raise FileNotFoundError("이미지를 찾을 수 없습니다. 경로를 다시 확인해주세요.")
# 2. 그레이스케일 변환
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 3. Canny Edge Detection
edges = cv2.Canny(gray, 100, 200)
# 4. 화면 출력용으로 리사이즈 (원본 파일은 그대로 두고, 표시만 축소)
h, w = img.shape[:2]
max_side = 800 # 화면에 보일 최대 크기 (원하시면 숫자만 조절하시면 됩니다.)
scale = min(max_side / max(h, w), 1.0) # 너무 작으면 키우지 않도록 1.0으로 제한
new_w = int(w * scale)
new_h = int(h * scale)
img_small = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA)
edges_small = cv2.resize(edges, (new_w, new_h), interpolation=cv2.INTER_AREA)
# 5. BGR → RGB 변환 (matplotlib은 RGB 기준)
img_small_rgb = cv2.cvtColor(img_small, cv2.COLOR_BGR2RGB)
# 6. matplotlib으로 나란히 출력
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(img_small_rgb)
plt.title("Original")
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(edges_small, cmap='gray')
plt.title("Canny Edge")
plt.axis('off')
plt.tight_layout()
plt.show()
th1을 100으로 th2를 200으로 놓고 나온 출력물입니다.

이번에는 th값을 달리하여 실험하도록 하겠습니다.
edges = cv2.Canny(gray, 60, 170)

th값을 줄이면 엣지 검출을 더 잘하게 되지만, 그만큼 노이즈도 많이 엣지로 나타나게 됩니다.