How to Extract Unique Colors with ImageMagick
This guide explains how to extract every unique color from an image to generate a custom palette strip using ImageMagick. You will learn the core command for isolating distinct pixels, how to scale the resulting palette for easy viewing, and how to limit the color count if your source image contains thousands of variations.
The Basic Command:
-unique-colors
ImageMagick provides a built-in operator called
-unique-colors. This operator scans an image, discards
duplicate color values, and outputs an image that is 1 pixel tall, with
a width equal to the total number of unique colors found.
For ImageMagick version 7, run:
magick input.png -unique-colors palette.pngFor ImageMagick version 6, run:
convert input.png -unique-colors palette.pngMaking the Palette Visible
Because the default output is only 1 pixel high, it is difficult to
view directly. You can resize the output into a visible swatch or strip
by chaining the -scale operator. Using -scale
rather than -resize preserves the exact, sharp edges of
each color block without anti-aliasing or blending.
To scale the palette into a 500x50 pixel strip:
magick input.png -unique-colors -scale 500x50! palette_bar.pngNote: The exclamation mark (!) forces the image to
stretch to the exact dimensions specified.
Limiting the Palette to Dominant Colors
Photographs often contain tens of thousands of unique shades due to
noise, compression artifacts, and subtle gradients. If you want a
concise palette of dominant colors rather than every individual pixel
variation, reduce the color count with the -colors operator
before extracting:
magick input.png +dither -colors 8 -unique-colors -scale 400x50! 8_color_palette.png+dither: Disables dithering to produce clean, solid blocks of color.-colors 8: Quantizes the image down to the 8 most representative colors.
Exporting Color Values to Text
If you need the hexadecimal or RGB values of the extracted palette along with the image, export the result directly to a text format:
magick input.png -unique-colors txt:colors.txtThis generates a plain-text file listing the hex code, RGB components, and color names for every unique color identified.