Advertisement
Guest User

Untitled

a guest
Jul 5th, 2015
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import argparse
  3.  
  4. import numpy
  5.  
  6. import PIL
  7. import PIL.ImageDraw
  8. import scipy
  9. import scipy.cluster
  10. import scipy.misc
  11.  
  12.  
  13. def main():
  14. parser = argparse.ArgumentParser()
  15. parser.add_argument('source_image')
  16. parser.add_argument('summary_image')
  17. parser.add_argument('-n', type=int, default=4)
  18. args = parser.parse_args()
  19. img = PIL.Image.open(args.source_image)
  20. c = args.n + 1
  21. colors = top_n_colors(img, top_n=args.n, num_of_clusters=c)
  22. save_summary_image(args.summary_image, colors)
  23.  
  24.  
  25. def pillow_image_to_simple_bitmap(pillow_image):
  26. small_img = pillow_image.resize((100, 100))
  27. bitmap = scipy.misc.fromimage(small_img)
  28. shape = bitmap.shape
  29. bitmap = bitmap.reshape(scipy.product(shape[:2]), shape[2])
  30. bitmap = bitmap.astype(numpy.float)
  31. return bitmap
  32.  
  33.  
  34. def top_n_colors(pillow_image, top_n, num_of_clusters):
  35. clustering = scipy.cluster.vq.kmeans
  36. bitmap = pillow_image_to_simple_bitmap(pillow_image)
  37. clusters, _ = clustering(bitmap, num_of_clusters)
  38. quntized, _ = scipy.cluster.vq.vq(bitmap, clusters)
  39. histgrams, _ = scipy.histogram(quntized, len(clusters))
  40. order = numpy.argsort(histgrams)[::-1][:top_n]
  41. for idx in range(top_n):
  42. rgb = clusters.astype(int)[order[idx]].tolist()
  43. yield '#{:02x}{:02x}{:02x}'.format(*rgb)
  44.  
  45.  
  46. def save_summary_image(path, color_codes, width=300, height=100):
  47. color_codes = tuple(color_codes)
  48. image = PIL.Image.new('RGB', (width, height))
  49. draw = PIL.ImageDraw.Draw(image)
  50. single_width = width / len(color_codes)
  51. for i, color_code in enumerate(color_codes):
  52. starting = (int(single_width * i), 0)
  53. ending = (int(single_width * (i + 1)), height)
  54. draw.rectangle([starting, ending], fill=color_code)
  55. image.save(path, format='png')
  56.  
  57.  
  58. if __name__ == '__main__':
  59. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement