티스토리 뷰

Coding/Python

python _ image 평균

잉_민 2022. 12. 10. 14:53
import sys

import numpy as np
import cv2
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import glob
import os

img_files = '/Users/l.smin/PycharmProjects/pythonProject/RGB/photo/100/A.jpg'

if not img_files:
    print ('jpg 없음...')
    sys.exit()


image = cv2.imread(img_files)


#img resize
resize_img = cv2.resize(image, (500, 500))

# 채널을 BGR -> RGB로 변경
resize_img = cv2.cvtColor(resize_img, cv2.COLOR_BGR2RGB)

resize_img = resize_img.reshape((resize_img.shape[0] * resize_img.shape[1], 3)) # height, width 통합 (차원)


#kmeans  k개의 데이터 평균을 만들어 데이터를 clustering하는 알고리즘
k = 5 # 1개의 평균값 구하겠다.
clt = KMeans(n_clusters = k)
clt.fit(resize_img)

center = clt.cluster_centers_




def centroid_histogram(clt):
    # grab the number of different clusters and create a histogram
    # based on the number of pixels assigned to each cluster
    numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)
    (hist, _) = np.histogram(clt.labels_, bins=numLabels)

    # normalize the histogram, such that it sums to one
    hist = hist.astype("float")
    hist /= hist.sum()

    # return the histogram
    return hist


hist = centroid_histogram(clt)
#print('percentage',hist)
#[ 0.68881873  0.09307065  0.14797794  0.04675512  0.02337756]

def plot_colors(hist, centroids):
    # initialize the bar chart representing the relative frequency
    # of each of the colors
    bar = np.zeros((50, 300, 3), dtype="uint8")
    startX = 0

    # loop over the percentage of each cluster and the color of
    # each cluster
    for (percent, color) in zip(hist, centroids):
        # plot the relative percentage of each cluster
        endX = startX + (percent * 300)
        cv2.rectangle(bar, (int(startX), 0), (int(endX), 50),
                      color.astype("uint8").tolist(), -1)
        startX = endX

    # return the bar chart
    return bar

bar = plot_colors(hist, clt.cluster_centers_)


# show our color bart
plt.figure()
plt.axis("off")
plt.imshow(bar)
plt.show()

#print(center)

input

output

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함