Guest User

Untitled

a guest
May 20th, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. # USAGE
  2. # python color_kmeans.py --image images/jp.png --clusters 3
  3. # or
  4. # python color_kmeans.py -g "images/chase*.png" -c9
  5.  
  6. # import the necessary packages
  7. from sklearn.cluster import KMeans
  8. import matplotlib.pyplot as plt
  9. import argparse
  10. import utils
  11. import cv2
  12. from PIL import Image
  13. import glob
  14. import time
  15.  
  16. current_milli_time = lambda: int(round(time.time() * 1000))
  17.  
  18. # construct the argument parser and parse the arguments
  19. ap = argparse.ArgumentParser()
  20. ap.add_argument("-i", "--image", required=False, help= "Path to the image")
  21. ap.add_argument("-g", "--glob", required=False, help= "Glob path")
  22. ap.add_argument("-c", "--clusters", required=True, type=int,help= "# of clusters")
  23. args = vars(ap.parse_args())
  24.  
  25. def makebar(img):
  26. outfile = "c%s_%s.gif" %( args["clusters"],current_milli_time() )
  27.  
  28. image = cv2.imread( img )
  29. image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  30. # save and show our image
  31. plt.close('all')
  32. plt.figure()
  33. plt.axis("off")
  34. # show source image
  35. # plt.imshow(image)
  36.  
  37. # reshape the image to be a list of pixels
  38. image = image.reshape((image.shape[0] * image.shape[1], 3))
  39.  
  40. # cluster the pixel intensities
  41. clt = KMeans(n_clusters = args["clusters"])
  42. clt.fit(image)
  43.  
  44. # build a histogram of clusters and then create a figure
  45. # representing the number of pixels labeled to each color
  46. hist = utils.centroid_histogram(clt)
  47. bar = utils.plot_colors(hist, clt.cluster_centers_)
  48.  
  49. im = Image.fromarray(bar)
  50. im.save(outfile)
  51.  
  52. # show our color bar
  53. plt.figure()
  54. plt.axis("off")
  55. plt.imshow(bar)
  56. plt.show()
  57.  
  58.  
  59. # load the image and convert it from BGR to RGB so that
  60. # we can display it with matplotlib
  61. if ( args["image"] ):
  62. files = glob.glob( args["image"] )
  63. else:
  64. files = glob.glob( args["glob"] )
  65. print("{{{{{{{{{{{{{ files }}}}}}}}}}}}}")
  66. print(files)
  67.  
  68.  
  69. for img in files:
  70. makebar(img)
Add Comment
Please, Sign In to add comment