Search code examples
imageimagemagickrmagickdragonfly-gem

Remap / posterize image colors using list of colors in imagemagick


Let's say I have this image:

Oranges

And I want to reduce the number of colors to 3, like so:

enter image description here

To do this, I applied the following command:

convert orange.jpg -remap palette.png orange_output.png

where palette.png looks like this: enter image description here

Is there a way to perform this conversion without the use of a palette image? Ideally, I would like to provide a list of colors and have it convert the image that way.


Solution

  • Is there a way to perform this conversion without the use of a palette image?

    Yes, but it wouldn't be as easy as providing a color palette. At a very high level, you would pre-process the source image by applying dither, dropping colors, and maybe even adjust tree-depth. After which it would be simple operation of replacing colors.

    convert source.jpg -colors 3 -treedepth 3 -dither FloydSteinberg +remap out.png
    

    Pre-process without colorswap

    omitting -draw color replace example

    But I imagine you really want an easy oneliner. Luckily remap accepts both text: format and pipes

    convert -size 1x1 xc:green xc:orange xc:blue -append txt:- | \
            convert source.jpg -remap txt:- out.png
    

    Remapped colors

    The text format is vary simple, and can be dynamically created & stored with any scripting language.

    # ImageMagick pixel enumeration: 1,3,65535,srgb
    0,0: (0%,50.1961%,0%)  #000080800000  green
    0,1: (100%,64.7059%,0%)  #FFFFA5A50000  orange
    0,2: (0%,0%,100%)  #00000000FFFF  blue
    

    You can probable reduce that down to...

    # ImageMagick pixel enumeration: 1,3,255,rgb
    0,0: #008000  green
    0,1: #FFA500  orange
    0,2: #0000FF  blue