Skip to content

Instantly share code, notes, and snippets.

@nkrumm
Created March 3, 2015 19:02
Show Gist options
  • Select an option

  • Save nkrumm/6f30ec920aa9a604e07a to your computer and use it in GitHub Desktop.

Select an option

Save nkrumm/6f30ec920aa9a604e07a to your computer and use it in GitHub Desktop.
Use k-means clustering to identify primary colors of an input image. Can specify --n-colors=INT. Also, --out-pallete=FILE will create a pallete of colors identified.
import argparse
import numpy as np
from scipy import ndimage
from scipy.cluster.vq import kmeans
from scipy.misc import imsave
def rgb2hex(r, g, b):
return '#{:02x}{:02x}{:02x}'.format(r, g, b)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("image", help="Path to image file to process.")
parser.add_argument("--n-colors", "-n", default=3, type=int, help="Number of colors to pick.")
parser.add_argument("--out-pallete", default=None, help="Make an optional pallete image.")
args = parser.parse_args()
img = ndimage.io.imread(args.image)
n_pixels = img.shape[0] * img.shape[1]
pixels = img[:, :, 0:3].reshape(n_pixels, 3)
result = kmeans(pixels, args.n_colors)
if args.out_pallete:
p = np.zeros((100 * args.n_colors, 100, 4))
for ix, color in enumerate(result[0]):
r, g, b = color
hexstr = rgb2hex(r, g, b)
print("(%d, %d, %d)\t(%s)" % (r, g, b, hexstr))
if args.out_pallete:
p[(ix * 100):((ix + 1)*100), :, 0:3] = color
p[(ix * 100):((ix + 1)*100), :, 3] = 255
if args.out_pallete:
imsave(args.out_pallete, p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment