How to Create an Image Histogram with ImageMagick?

This article provides a step-by-step guide on how to use the ImageMagick convert command to generate a histogram from an image. You will learn the exact command-line syntax required to extract color data, visualize it as a graphical chart, or output it as a text-based list of pixel counts. Whether you need a visual representation of an image’s tonal distribution or raw data for analysis, ImageMagick offers efficient built-in tools to accomplish the task.

Understanding the Histogram Format in ImageMagick

ImageMagick allows you to generate histograms in two primary ways: a visual image file (like a PNG chart) or a text file containing the exact pixel counts for every color present in the image. The special histogram: delegate tells ImageMagick to process the input image and format the output specifically as a histogram.

Method 1: Generating a Visual Histogram Image

If you want to create a standard graphical chart that visualizes the distribution of tones or colors in your image, you can append the histogram: prefix to your output file name.

magick convert input.jpg histogram:output.png

Note: In ImageMagick v7 and later, the modern syntax uses magick instead of magick convert, but the behavior remains identical.

When you run this command, ImageMagick analyzes the color channels of input.jpg and produces a unique output.png image. This output is a structured chart displaying the frequency of pixels across different intensity levels, usually separated by color channels (Red, Green, Blue, and Composite).

Method 2: Outputting Histogram Data to a Text File

Sometimes you need the raw numbers behind the image rather than a visual chart. You can use ImageMagick to export a text list of every unique color in the image alongside the exact number of pixels that use that color.

magick convert input.jpg -format "%c" histogram:info:output.txt

Breaking Down the Command:

The resulting text file will look similar to this:

    25148: (  0,  0,  0) #000000 black
     4123: (255,255,255) #FFFFFF white
      842: (255,  0,  0) #FF0000 red

The first column shows the exact pixel count, followed by the RGB values, the hex code, and the human-readable color name if applicable.

Advanced Option: Isolating Specific Channels

If you only want a histogram of a single channel (such as the grayscale intensity or just the blue channel), you can isolate the channel before generating the histogram.

magick convert input.jpg -colorspace gray histogram:output_gray.png

By converting the image to the gray colorspace first, the resulting histogram chart will strictly reflect the luminance (brightness) values of the image from pure black to pure white, stripping away individual color channel data.