Created
March 17, 2015 22:52
-
-
Save douglasgoodwin/1456ce09e4943dbf6be9 to your computer and use it in GitHub Desktop.
fast way to generate weighted bar palettes from images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# USAGE | |
# python color_kmeans.py --image images/jp.png --clusters 3 | |
# or | |
# python color_kmeans.py -g "images/chase*.png" -c9 | |
# import the necessary packages | |
from sklearn.cluster import KMeans | |
import matplotlib.pyplot as plt | |
import argparse | |
import utils | |
import cv2 | |
from PIL import Image | |
import glob | |
import time | |
current_milli_time = lambda: int(round(time.time() * 1000)) | |
# construct the argument parser and parse the arguments | |
ap = argparse.ArgumentParser() | |
ap.add_argument("-i", "--image", required=False, help= "Path to the image") | |
ap.add_argument("-g", "--glob", required=False, help= "Glob path") | |
ap.add_argument("-c", "--clusters", required=True, type=int,help= "# of clusters") | |
args = vars(ap.parse_args()) | |
def makebar(img): | |
outfile = "c%s_%s.gif" %( args["clusters"],current_milli_time() ) | |
image = cv2.imread( img ) | |
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) | |
# save and show our image | |
plt.close('all') | |
plt.figure() | |
plt.axis("off") | |
# show source image | |
# plt.imshow(image) | |
# reshape the image to be a list of pixels | |
image = image.reshape((image.shape[0] * image.shape[1], 3)) | |
# cluster the pixel intensities | |
clt = KMeans(n_clusters = args["clusters"]) | |
clt.fit(image) | |
# build a histogram of clusters and then create a figure | |
# representing the number of pixels labeled to each color | |
hist = utils.centroid_histogram(clt) | |
bar = utils.plot_colors(hist, clt.cluster_centers_) | |
im = Image.fromarray(bar) | |
im.save(outfile) | |
# show our color bar | |
plt.figure() | |
plt.axis("off") | |
# plt.imshow(bar) | |
# plt.show() | |
# load the image and convert it from BGR to RGB so that | |
# we can display it with matplotlib | |
if ( args["image"] ): | |
files = glob.glob( args["image"] ) | |
else: | |
files = glob.glob( args["glob"] ) | |
print("{{{{{{{{{{{{{ files }}}}}}}}}}}}}") | |
print(files) | |
for img in files: | |
makebar(img) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment