This time, we will get the main color from the loaded image. We will divide the normal color Pokemon and the different color Pokemon into 5 main colors so that you can compare them.
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import argparse
import utils
import cv2
import numpy as np
When the image is read by OpenCV, it is converted to RGB because it is BGR as it is.
image_path = "./Wonoragon 00001.jpg "
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
Form a NumPy array into a list of RGB pixels.
image = image.reshape((image.shape[0] * image.shape[1], 3))
k-means
Use k-means to find the most dominant color. Make the number of clusters 5 and cluster the list of RGB pixels.
clt = KMeans(n_clusters = 5)
clt.fit(image)
Find the percentage of the main color from the histogram.
numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)
(hist, _) = np.histogram(clt.labels_, bins=numLabels)
hist = hist.astype("float")
hist /= hist.sum()
Use the for statement to extract the five main colors and their ratios.
bar = np.zeros((50, 300, 3), dtype="uint8")
cluster_centers_arr = clt.cluster_centers_.astype(int, copy=False)
startX = 0
for (percent, color) in zip(hist, cluster_centers_arr):
color_hex_str = '#%02x%02x%02x' % tuple(color)
print(percent , color_hex_str)
endX = startX + (percent * 300)
cv2.rectangle(bar, (int(startX), 0), (int(endX), 50),color.astype("uint8").tolist(), -1)
startX = endX
Displays 5 main colors.
plt.figure()
plt.axis("off")
plt.imshow(bar)
plt.show()
Original screenshot (Wonoragon)
Execution result
0.7486892361111112 #dd4928
0.05908420138888889 #0b0403
0.038871527777777776 #b7d1e0
0.13411458333333334 #d21d1d
0.01924045138888889 #294e37
Original screenshot (different color Wonoragon)
Execution result
0.7698796296296296 #dd4828
0.03972407407407407 #c9d0ca
0.026488888888888888 #262220
0.025824074074074076 #6e6166
0.13808333333333334 #d41d1a
I was able to get 5 main colors, but if it was left as it was, the proportion of the background would increase. Because I was able to get the main color of Pokemon from the three colors excluding the main color of the background color From there, it seems that you can judge whether it is a different color.
OpenCV and Python K-Means Color Clustering
Extract the main color from the image in Python
Recommended Posts