[Python] Get the main color from the screenshot

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.

import

from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import argparse
import utils
import cv2
import numpy as np

Image acquisition

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()

Get the main color

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()

Execution result

Original screenshot (Wonoragon) ウオノラゴン.png

Execution result

0.7486892361111112 #dd4928
0.05908420138888889 #0b0403
0.038871527777777776 #b7d1e0
0.13411458333333334 #d21d1d
0.01924045138888889 #294e37
通常配色.png

Original screenshot (different color Wonoragon) 色違いウオノラゴン.png

Execution result

0.7698796296296296 #dd4828
0.03972407407407407 #c9d0ca
0.026488888888888888 #262220
0.025824074074074076 #6e6166
0.13808333333333334 #d41d1a
色違い配色.png

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.

reference

OpenCV and Python K-Means Color Clustering

Extract the main color from the image in Python

Recommended Posts

[Python] Get the main color from the screenshot
Get the contents of git diff from python
[Python] Get the text of the law from the e-GOV Law API
Get the return code of the Python script from bat
[Python] Adjusting the color bar
[Python] Get the previous month
Get your heart rate from the fitbit API in Python!
Get the value while specifying the default value from dict in Python
Get the desktop path in Python
Existence from the viewpoint of Python
Get the weather with Python requests
Get the weather with Python requests 2
Get the script path in Python
[Python] Adjusted the color map standard
How to get the Python version
Use the Flickr API from Python
Get the value from the [Django] Form
Get upcoming weather from python weather api
Get the desktop path in Python
Get the host name in Python
Python Note: Get the current month
How to get followers and followers from python using the Mastodon API
[Python] Get the update date of a news article from HTML
Get html from element with Python selenium
Get exchange rates from open exchange rates in Python
[Note] Get data from PostgreSQL with Python
Get keystrokes from / dev / input (python evdev)
Learning notes from the beginning of Python 1
[Python] Get the variable name with str
Get battery level from SwitchBot in Python
Launch the Python interpreter from Git bash
From Python 3.4, pip becomes the standard installer! ??
[Python] Get the character code of the file
Get the EDINET code list in Python
Get Precipitation Probability from XML in Python
Get the address from latitude and longitude
Get wordpress posts from the past week
Learning notes from the beginning of Python 2
Get only the text from the Django form.
Get metric history from MLflow in Python
Get time series data from k-db.com in Python
Get the weather in Osaka via WebAPI (python)
[Python] Get / edit the scale label of the figure
Get the caller of a function in Python
[Bash] Use here-documents to get python power from bash
sql from python
Get the X Window System window title in Python
[Python] Get the last updated date of the website
MeCab from Python
How to get the files in the [Python] folder
Get BTC / JPY board information from Python --bitflyer
[Python] I tried to get the type name as a string from the type function
Use the nghttp2 Python module from Homebrew from pyenv's Python
[Python] Get the day of the week (English & Japanese)
Get only articles from web pages in Python
Try accessing the YQL API directly from Python 3
Get the update date of the Python memo file.
Get the value of a specific key in a list from the dictionary type in the list with Python
Pass an array from PHP to PYTHON and do numpy processing to get the result
[Python] How to remove duplicate values from the list
The wall of changing the Django service from Python 2.7 to Python 3