소개
이 실습에서는 스펙트럴 클러스터링을 사용하여 이미지 분할하는 방법을 배웁니다. 여러 개의 연결된 원이 있는 이미지를 생성하고 스펙트럴 클러스터링을 사용하여 원들을 분리합니다.
VM 팁
VM 시작이 완료되면 왼쪽 상단 모서리를 클릭하여 Notebook 탭으로 전환하여 연습을 위한 Jupyter Notebook에 접근합니다.
때때로 Jupyter Notebook 이 완전히 로드되기까지 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사를 자동화할 수 없습니다.
학습 중 문제가 발생하면 Labby 에게 문의하십시오. 세션 후 피드백을 제공하면 문제를 신속하게 해결해 드리겠습니다.
데이터 생성
NumPy 를 사용하여 네 개의 원이 있는 이미지를 생성합니다. 그런 다음 이미지에 노이즈를 추가하고 마스크를 생성하여 이미지를 전경으로 제한합니다.
import numpy as np
l = 100
x, y = np.indices((l, l))
center1 = (28, 24)
center2 = (40, 50)
center3 = (67, 58)
center4 = (24, 70)
radius1, radius2, radius3, radius4 = 16, 14, 15, 14
circle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1**2
circle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2**2
circle3 = (x - center3[0]) ** 2 + (y - center3[1]) ** 2 < radius3**2
circle4 = (x - center4[0]) ** 2 + (y - center4[1]) ** 2 < radius4**2
img = circle1 + circle2 + circle3 + circle4
mask = img.astype(bool)
img = img.astype(float)
img += 1 + 0.2 * np.random.randn(*img.shape)
이미지를 그래프로 변환
sklearn.feature_extraction.image의 img_to_graph를 사용하여 이미지를 그래프로 변환합니다. 에지의 기울기 값도 계산됩니다.
from sklearn.feature_extraction import image
graph = image.img_to_graph(img, mask=mask)
스펙트럼 군집화
sklearn.cluster의 spectral_clustering 함수를 사용하여 스펙트럼 군집화를 수행합니다. n_clusters 매개변수를 4 로 설정하여 네 개의 원을 분리합니다.
from sklearn.cluster import spectral_clustering
labels = spectral_clustering(graph, n_clusters=4, eigen_solver="arpack")
결과 플롯
matplotlib.pyplot의 matshow를 사용하여 원본 이미지와 분할된 이미지를 나란히 플롯합니다.
import matplotlib.pyplot as plt
label_im = np.full(mask.shape, -1.0)
label_im[mask] = labels
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))
axs[0].matshow(img)
axs[1].matshow(label_im)
plt.show()
두 개의 원 플롯
위의 과정을 반복하지만, 생성된 첫 두 개의 원만 고려합니다.
img = circle1 + circle2
mask = img.astype(bool)
img = img.astype(float)
img += 1 + 0.2 * np.random.randn(*img.shape)
graph = image.img_to_graph(img, mask=mask)
graph.data = np.exp(-graph.data / graph.data.std())
labels = spectral_clustering(graph, n_clusters=2, eigen_solver="arpack")
label_im = np.full(mask.shape, -1.0)
label_im[mask] = labels
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))
axs[0].matshow(img)
axs[1].matshow(label_im)
plt.show()
요약
이 실험에서 스펙트럴 클러스터링을 사용하여 이미지 분할하는 방법을 배웠습니다. 여러 개의 연결된 원이 있는 이미지를 생성하고, 이 이미지를 그래프로 변환한 후 스펙트럴 클러스터링을 수행하고 결과를 플롯했습니다.