Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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)
Add Comment
Please, Sign In to add comment