Replace rgb values of image by a new color with the same shades as earlier in python

Viewed 77

Given an image, I'd like to change the rgb values of the most dominant colors by the same gradient.

I have read an image and performed k means clustering on it in order to obtain the most color values below -

import scipy.cluster
import sklearn.cluster
import numpy
from PIL import Image

def dominant_colors(image):  # PIL image input

    image = image.resize((150, 150))      # optional, to reduce time
    ar = numpy.asarray(image)
    shape = ar.shape
    ar = ar.reshape(numpy.product(shape[:2]), shape[2]).astype(float)

    kmeans = sklearn.cluster.MiniBatchKMeans(
        n_clusters=10,
        init="k-means++",
        compute_labels=True,
        max_iter=20,
        random_state=1000,
    ).fit(ar)
   # print(kmeans)

    codes = kmeans.cluster_centers_

    vecs, _dist = scipy.cluster.vq.vq(ar, codes)  
    
    counts, _bins = numpy.histogram(vecs, len(codes))  
   # print(counts)
      # count occurrences

    colors = []
    for index in numpy.argsort(counts)[::-1]:
        colors.append(tuple([int(code) for code in codes[index]]))
    return colors       

This gives me the cluster centroids of the top 10 most dominant colors -


[(222, 187, 108),
 (231, 209, 138),
 (203, 158, 68),
 (37, 34, 20),
 (227, 237, 232),
 (184, 195, 187),
 (147, 103, 32),
 (173, 158, 109),
 (92, 93, 71),
 (139, 153, 150)]

I have also obtained the cluster values of each value via kmeans.labels_

Now I'd like to change all values of my first cluster to red. However I dont want all pixels to be a monotonous red, I want them to be spread in the same variation/gradient as they were originally.

For example cluster 1 represent shades of the color beige, I want to now represent shades of red in the same variation.

0 Answers
Related