<jupyter_start><jupyter_text>Extract RGB values from imageThere are broadly three steps to find the dominant colors in an image:Extract RGB values into three lists.Perform k-means clustering on scaled RGB values.Display the colors of cluster centers.To extract RGB values, we use the imread() function of the image class of matplotlib. Empty lists, r, g and b have been initialized.For the purpose of finding dominant colors, we will be using the following image.<jupyter_code>import matplotlib.image as img

r = []
g = []
b = []

# Read batman image
batman_image = img.imread('datasets/batman.jpg')
print(batman_image.shape)

for row in batman_image:
    for temp_r, temp_g, temp_b in row:
        r.append(temp_r)
        g.append(temp_g)
        b.append(temp_b)

batman_df = pd.DataFrame({'red':r, 'green':b, 'blue':b})
display(batman_df.head())
from scipy.cluster.vq import whiten

columns = ['red', 'green', 'blue']
for column in columns:
    batman_df['scaled_'+ column] = whiten(batman_df[column])

display(batman_df.head())

from sklearn.preprocessing import StandardScaler

# Create scaler
scaler = StandardScaler(with_mean=False, with_std=True)

batman_df[['scaled_red', 'scaled_green', 'scaled_blue']] = scaler.fit_transform(batman_df[['red','green','blue']])
display(batman_df.shape)
display(batman_df.head())<jupyter_output><empty_output><jupyter_text>How many dominant colors?We have loaded the following image using the imread() function of the image class of matplotlib.The RGB values are stored in a data frame, batman_df. The RGB values have been standardized used the whiten() function, stored in columns, scaled_red, scaled_blue and scaled_green.Construct an elbow plot with the data frame. How many dominant colors are present?<jupyter_code>from scipy.cluster.vq import kmeans, vq

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

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

# Create a data frame with two lists, num_clusters and distortions
elbow_plot = pd.DataFrame({'num_clusters':num_clusters, 'distortions':distortions})

# Create a line plot of num_clusters and distortions
sns.lineplot(x='num_clusters', y='distortions', data = elbow_plot)
plt.xticks(num_clusters)
plt.show()
from sklearn.cluster import KMeans

num_clusters = range(1, 7)
inertias = []

for k in num_clusters:
    # Create a KMeans with k clusters
    model = KMeans(n_clusters=k)

    # Fit model to samples
    model.fit(batman_df[['scaled_red', 'scaled_green', 'scaled_blue']])

    # Append iterntia to the list of inertias
    inertias.append(model.inertia_)

# Create a data frame with two lists - num_clusters, distortions
elbow_plot = pd.DataFrame({'num_clusters': num_clusters, 'inertias': inertias})

# Creat a line plot of num_clusters and distortions
sns.lineplot(x='num_clusters', y='inertias', data = elbow_plot)
plt.show()<jupyter_output><empty_output><jupyter_text>RESULT: Notice that there are three distinct colors present in the image, which is supported by the elbow plot.  Display dominant colorsWe have loaded the following image using the imread() function of the image class of matplotlib.To display the dominant colors, convert the colors of the cluster centers to their raw values and then converted them to the range of 0-1, using the following formula: ```converted_pixel = standardized_pixel * pixel_std / 255```The RGB values are stored in a data frame, batman_df. The scaled RGB values are stored in columns, scaled_red, scaled_blue and scaled_green. The cluster centers are stored in the variable cluster_centers, which were generated using the kmeans() function with three clusters.<jupyter_code>colors = []
cluster_centers, distortion = kmeans(batman_df[['scaled_red', 'scaled_green', 'scaled_blue']], 3)

# Get standard deviations of each color
r_std, g_std, b_std = batman_df[['red', 'green', 'blue']].std()
display(r_std, g_std, g_std)


for cluster_center in cluster_centers:
    scaled_r, scaled_g, scaled_b = cluster_center
    # Convert each standardized value to scaled value
    colors.append((
        scaled_r * r_std / 255,
        scaled_g * g_std / 255,
        scaled_b * b_std / 255
    ))

plt.imshow([colors])
plt.show()
model = KMeans(n_clusters=3)
model.fit(batman_df[['scaled_red', 'scaled_green', 'scaled_blue']])
centroids = model.cluster_centers_
display(centroids)

centroids_unscaled = scaler.inverse_transform(centroids)
display(centroids_unscaled)

centroids_unscaled /= 255
display(centroids_unscaled)

plt.imshow([centroids_unscaled])
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09672619047619048, 'fraction_numerical': 0.004889455782312925, 'mean_word_length': 5.480716253443526, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '4202', 'license': 'MIT', 'n_tokens_mistral': 1591, 'n_tokens_neox': 1515, 'n_words': 476, 'path': 'courses/cluster_analysis/cluster_analysis2.ipynb', 'repo_name': 'albertoarenas/datacamp', 'size': '4704'}