Guest User

Untitled

a guest
May 27th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. KeyError: 'purple'
  2.  
  3. import numpy as np
  4.  
  5. from matplotlib import colors
  6. from scipy.spatial import cKDTree as KDTree
  7. from scipy.misc import face
  8. from PIL import Image
  9.  
  10. REDUCED_COLOR_SPACE = True
  11.  
  12. # borrow a list of named colors from matplotlib
  13. if REDUCED_COLOR_SPACE:
  14. use_colors = {k: colors.cnames[k] for k in ['red', 'green', 'blue', 'black', 'yellow', 'purple']}
  15. else:
  16. use_colors = colors.cnames
  17.  
  18. # translate hexstring to RGB tuple
  19. named_colors = {k: tuple(map(int, (v[1:3], v[3:5], v[5:7]), 3*(16,)))
  20. for k, v in use_colors.items()}
  21. ncol = len(named_colors)
  22.  
  23. if REDUCED_COLOR_SPACE:
  24. ncol -= 1
  25. no_match = named_colors.pop('purple')
  26. else:
  27. no_match = named_colors['purple']
  28.  
  29. # make an array containing the RGB values
  30. no_match = named_colors['purple']
  31. color_tuples = list(named_colors.values())
  32. color_tuples.append(no_match)
  33. color_tuples = np.array(color_tuples)
  34.  
  35. color_names = list(named_colors)
  36. color_names.append('no match')
  37.  
  38. # get example picture
  39. img = Image.open('apple.jpg')
  40.  
  41. # build tree
  42. tree = KDTree(color_tuples[:-1])
  43. # tolerance for color match `inf` means use best match no matter how
  44. # bad it may be
  45. tolerance = np.inf
  46. # find closest color in tree for each pixel in picture
  47. dist, idx = tree.query(img, distance_upper_bound=tolerance)
  48. # count and reattach names
  49. counts = dict(zip(color_names, np.bincount(idx.ravel(), None, ncol+1)))
  50.  
  51. print(counts)
  52.  
  53. import pylab
  54.  
  55. pylab.imshow(img)
  56. pylab.savefig('apple.jpg')
  57. pylab.clf()
  58. pylab.imshow(color_tuples[idx])
  59. pylab.savefig('minimal.png' if REDUCED_COLOR_SPACE else 'reduced.png')
Add Comment
Please, Sign In to add comment