title: How to generate a matplotlib colormap from from an image of a colour scale?
body: <p>I took a screenshot of a colour scale I would like to use with matplotlib. What is a good/easy way I could generate a matplotlib colormap object from this image?</p>
  
  <p><a href="https://i.stack.imgur.com/jrUR2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jrUR2.png" alt="colorbar screenshot"></a></p>
  
  <p>Edit: Here's my attempt at this:</p>
  
  <pre><code>from PIL import Image
  import matplotlib
  from matplotlib import pyplot as plt
  import numpy as np
  
  img = Image.open('pet_colourbar.png')
  data = img.load()
  
  # Loop through pixels and extract rgb value
  rgb_colours = []
  for i in range(img.size[1]):
      rgb = [x/255 for x in data[0, i]]  # scale values 0-1
      rgb_colours.append(rgb)
  
  pet_cmap = matplotlib.colors.ListedColormap(rgb_colours[::-1])  # reverse order
  
  # Plot example gradient
  gradient = np.linspace(0, 1, 256)
  gradient = np.vstack((gradient, gradient))
  plt.imshow(gradient, aspect='auto', cmap=pet_cmap)
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/Ta3iW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ta3iW.png" alt="Matplotlib colorbar"></a></p>