이미지의 지배 색상

Python으로 배우는 군집 분석

Shaumik Daityari

Business Analyst

이미지의 지배 색상

  • 모든 이미지는 픽셀로 구성됩니다
  • 각 픽셀에는 세 값이 있습니다: Red, Green, Blue
  • 픽셀 색상: 이 RGB 값의 조합
  • 표준화된 RGB로 k-평균을 수행해 군집 중심을 찾습니다
  • 활용: 위성 이미지에서 특징 식별
Python으로 배우는 군집 분석

위성 이미지의 특징 식별

Python으로 배우는 군집 분석

지배 색상 찾기 도구

  • 이미지를 픽셀로 변환: matplotlib.image.imread
  • 군집 중심의 색 표시: matplotlib.pyplot.imshow
Python으로 배우는 군집 분석

Python으로 배우는 군집 분석

이미지를 RGB 행렬로 변환

import matplotlib.image as img
image = img.imread('sea.jpg')
image.shape
(475, 764, 3)
r = []
g = []
b = []

for row in image:
    for pixel in row:
        # A pixel contains RGB values
        temp_r, temp_g, temp_b = pixel
        r.append(temp_r)
        g.append(temp_g)
        b.append(temp_b)
Python으로 배우는 군집 분석

RGB 값으로 DataFrame 생성

pixels = pd.DataFrame({'red': r,
                       'blue': b,
                       'green': g})
pixels.head()
red blue green
252 255 252
75 103 81
... ... ...
Python으로 배우는 군집 분석

엘보우 플롯 생성

distortions = []
num_clusters = range(1, 11)

# Create a list of distortions from the kmeans method
for i in num_clusters:
    cluster_centers, _ = kmeans(pixels[['scaled_red', 'scaled_blue', 
                                        'scaled_green']], i)
    distortions.append(distortion)

# Create a DataFrame with two lists - number of clusters and distortions
elbow_plot = pd.DataFrame({'num_clusters': num_clusters, 
                           'distortions': distortions})

# Creat a line plot of num_clusters and distortions
sns.lineplot(x='num_clusters', y='distortions', data = elbow_plot)
plt.xticks(num_clusters)
plt.show()
Python으로 배우는 군집 분석

엘보우 플롯

Python으로 배우는 군집 분석

지배 색상 찾기

cluster_centers, _ = kmeans(pixels[['scaled_red', 'scaled_blue', 
                                    'scaled_green']], 2)
colors = []

# Find Standard Deviations
r_std, g_std, b_std = pixels[['red', 'blue', 'green']].std()

# Scale actual RGB values in range of 0-1
for cluster_center in cluster_centers:
    scaled_r, scaled_g, scaled_b = cluster_center
    colors.append((
        scaled_r * r_std/255,
        scaled_g * g_std/255,
        scaled_b * b_std/255
    ))
Python으로 배우는 군집 분석

지배 색상 표시

#Dimensions: 2 x 3 (N X 3 matrix)
print(colors)
[(0.08192923122023911, 0.34205845943857993, 0.2824002984155429),
 (0.893281510956742, 0.899818770315129, 0.8979114272960784)]
#Dimensions: 1 x 2 x 3 (1 X N x 3 matrix)
plt.imshow([colors]) 
plt.show()

Python으로 배우는 군집 분석

다음: 연습 문제

Python으로 배우는 군집 분석

Preparing Video For Download...