title: How do I use Pillow's Image.convert() with a custom color palette?
body: <p>I want to reduce the bit depth (color depth) of an image down to a set of custom colours in Python. Essentially to give the program a set of x colors and have it associate each pixel in a full color image with the closest color from the given list. I am having trouble with the Pillow library as evidenced below.</p>
  <p>This code will correctly reduce the colors in image 'Z.png' down to only 4 colors, based on a palette of colors created from the image itself:</p>
  <pre><code>from PIL import Image
  
  colorImage = Image.open(&quot;Z.png&quot;)
  imageWithColorPalette = colorImage.convert(&quot;P&quot;, palette=Image.ADAPTIVE, colors=4)
  imageWithColorPalette.save(&quot;Output.png&quot;)
  
  from IPython.display import Image
  Image('Output.png')
  </code></pre>
  <p>This code is similar except I have attempted to use my own color palette. The problem is this code returns the exact same image as the above code and seems to just go with an adaptive palette and ignore the custom one I have attempted to specify:</p>
  <pre><code>from PIL import Image
  
  pall = [
      0, 0, 0,
      255, 0, 0,
      255, 255, 0,
      255, 153, 0,
  ]
  
  colorImage = Image.open(&quot;Z.png&quot;)
  imageWithColorPalette = colorImage.convert(&quot;P&quot;, palette=pall, colors=4)
  imageWithColorPalette.save(&quot;Output.png&quot;)
  
  from IPython.display import Image
  Image('Output.png')
  </code></pre>
  <p>Based on the documentaion from here:
  <a href="https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.convert" rel="nofollow noreferrer">https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.convert</a>
  and here
  <a href="https://pillow.readthedocs.io/en/3.0.x/reference/ImagePalette.html" rel="nofollow noreferrer">https://pillow.readthedocs.io/en/3.0.x/reference/ImagePalette.html</a>. I assume my <em>pall</em> is given in an incorrect format/size or that I need to include a <em>matrix</em> argument in the <em>convert</em> method. According to the documentation the <em>matrix</em> argument is <strong>'An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values.'</strong> which I am unsure how to implement.</p>
  <p>Whatever the problem is I'm very stuck and would appriciate some help.</p>
  <p>Alternativley, is there a better Python library to use for this task as I'm open to suggestions.</p>