How to Use ImageMagick Convert for Pixel Math?

ImageMagick’s convert command (or magick in newer versions) provides powerful tools for manipulating images by applying mathematical operations directly to pixel values. By leveraging operators like -fx, -evaluate, and -combine, users can perform basic arithmetic, evaluate complex expressions, or blend channels using precise formulas. This article walks through the primary methods for executing pixel-level math, ranging from simple global adjustments to complex, per-pixel custom equations.

The -evaluate Operator for Simple Arithmetic

For straightforward mathematical operations applied uniformly to every pixel in an image, the -evaluate operator is the most efficient choice. It requires a method (such as Add, Subtract, Multiply, Divide, or Log) and a constant value.

Using -evaluate is highly optimized and executes rapidly because the same calculation is applied identically across the entire image matrix.

The -fx Operator for Complex Custom Formulas

When an operation requires different logic per pixel, depends on pixel coordinates, or needs to reference multiple channels, the -fx operator is the ideal tool. It allows you to write custom mathematical expressions using a built-in mini-language.

The expression can utilize various native variables and functions:

For example, to create a horizontal gradient by multiplying the red channel by its relative X-coordinate, you can use:

magick input.jpg -fx "u.r * (i/w)" output.jpg

Note: While incredibly powerful, the -fx operator interprets expressions dynamically for every single pixel, making it significantly slower than native operators on large images.

Multi-Image Math with Channel Operators

ImageMagick can also perform mathematical operations between two or more distinct images. The -compose operator combined with -composite allows you to add, subtract, or multiply the pixel values of one image against another.

For advanced multi-image mathematics where you want to apply a specific formula to multiple inputs simultaneously, the -poly (polynomial) operator or -evaluate-sequence operator can be used to calculate sums, averages, or weighted totals across an entire stack of images.