The FX special effects image operator applies mathematical expressions to each pixel channel of an image. The FX expression language provides a flexible mechanism for fine-grained pixel-level transformations, analysis, and procedural generation.
Create procedural canvases, gradients, and mathematical colormaps from equations.
Translate, flip, mirror, rotate, scale, shear, and warp images using custom coordinate functions.
Move color values between images and channels, convolve neighboring pixels, and merge multiple inputs.
Compute statistical metrics, evaluate properties, and generate custom image "fingerprints."
-fx vs. +fx):
The operator loops through all pixels and active channels, replacing the entire image sequence with a modified clone of the first image (u). Other images in the sequence serve only as reference data unless +fx is used to apply the expression to every image in the sequence individually.
debug(), which forces single-threaded execution for clean console output.
Examples & Scripting Workflows
Inject Box-Muller Gaussian random noise scaled per color channel:
myn=sqrt(-2*ln(rone))*cos(2*Pi*rtwo); myntwo=sqrt(-2*ln(rtwo))* \
cos(2*Pi*rone); pnoise=sqrt(p)*myn*sqrt(iso)* \
channel(4.28,3.86,6.68)/255; max(0,p+pnoise)' noisy.png
Use an iterative for() loop to render a Julia set fractal and map escape iterations through a color lookup table (-clut):
Xi=2.4*i/w-1.2; \
Yj=2.4*j/h-1.2; \
for (pixel=0.0, (hypot(Xi,Yj) < 2.0) && (pixel < 1.0), \
delta=Xi^2-Yj^2; \
Yj=2.0*Xi*Yj+0.2; \
Xi=delta+0.4; \
pixel+=0.00390625 \
); \
pixel == 1.0 ? 0.0 : pixel" \
\( -size 1x1 xc:white xc:red xc:orange xc:yellow xc:green1 xc:cyan xc:blue \
xc:blueviolet xc:white -reverse +append -filter Cubic -resize 1024x1! \) \
-clut -rotate -90 julia-set.png
Print the first 10 prime numbers to standard output using nested for() loops and debug():
for (prime=2, prime < 30, composite=0; \
for (nn=2, nn < (prime/2+1), if ((prime % nn) == 0, composite++, ); nn++); \
if (composite <= 0, debug(prime), ); prime++)" null:
For more script examples, visit Using FX, The Special Effects Image Operator.
The Anatomy of an FX Expression
Formal building blocks recognized by the FX expression parser:
| Element | Specification & Examples |
|---|---|
| Numbers | Integers, floating-point values, scientific notation (explicit +/- required on exponent, e.g., 3.81469e-06), and International System / IEC postfixes (KB, MiB, GB, etc.). |
| Color Names | Named ImageMagick colors such as red, green, blue, cyan, black. |
| Color Hex Values | 3-, 6-, or 8-digit hexadecimal color specifications such as #ccc, #cbfed0, or #b9e1cc00. |
| Color Functions | srgb(), srgba(), rgb(), rgba(), cmyk(), cmyka(), hsl(), hsla(), etc. |
| Channel Constructor | channel(...) accepts 0 to 5 arguments and returns the value matching the channel currently being processed (in order RGBKA or CMYKA), zeroing omitted trailing channels (e.g., channel(0.1) sets the first channel to 0.1 and others to 0). |
| Array Storage | An image acts as 2D array storage bounded by its width and height (e.g., p[-1,-1].r), and an image sequence provides multiple arrays (e.g., u.p[0,0].r, v.p[0,0].r). Storage precision is Quantum-limited ([0..65535] for Q16) or floating-point on HDRI-enabled builds. |
| User Settings | Define reusable FX symbols via image options, e.g.:$ magick ... -set option:wd1 "%[fx:w/2]" -resize "%[fx:wd1-5]" ... |
| Symbol | Description |
|---|---|
| u, v | First (u) and second (v) images in the sequence list. |
| s, t, n | Current image in list (s; equals u outside %[fx:]), current image index (t), and total image count (n). |
| i, j, p | Column offset (i), row offset (j), and pixel accessor (p, absolute or relative to current pixel). |
| w, h, z | Image width (w), height (h), and channel depth (z). |
| r, g, b, a, o | Red, green, blue, alpha, and opacity values (from RGBA) of a specific or current pixel. |
| c, m, y, k | Cyan, magenta, yellow, and black values of a CMYK pixel. |
| all, this | Channel specifiers targeting all channels (all) or the active channel being processed (this). |
| intensity | Pixel intensity, respecting the -intensity setting. |
| hue, saturation | Pixel hue and saturation components. |
| lightness | Pixel lightness: 0.5*max(red,green,blue) + 0.5*min(red,green,blue). |
| luma, luminance | Pixel luma / luminance: 0.212656*red + 0.715158*green + 0.072186*blue. |
| page.width, page.height, page.x, page.y | Virtual canvas page dimensions and x/y offsets. |
| printsize.x, printsize.y | Horizontal and vertical print size. |
| resolution.x, resolution.y | Horizontal and vertical image resolution. |
| depth, extent | Image bit depth and file extent. |
| minima, maxima, mean, median | Whole-image statistics. Append a channel specifier for per-channel stats (e.g., depth.r, mean.this, mean.all). |
| standard_deviation, kurtosis, skewness | Statistical dispersion, kurtosis, and skewness across the image or a specified channel. |
| s.depth, s.kurtosis, s.maxima, s.mean, s.median, s.minima, s.resolution.x, s.resolution.y, s.skewness, s.standard_deviation | Image attributes prefixed by image reference (s., u., v., or image.). |
| Constant | Value / Description |
|---|---|
| E, e | Euler's number (2.7182818...) |
| Epsilon, epsilon | Floating-point comparison tolerance (1.0 × 10⁻¹²) |
| Opaque | Full opacity constant (1.0) |
| PHI, phi | Golden ratio (1.6180339...) |
| PI, Pi, pi | Archimedes' constant π (3.14159265359...) |
| QuantumRange, quantumrange | Maximum pixel channel value for the build depth (255 for Q8, 65535 for Q16) |
| QuantumScale, quantumscale | Reciprocal of QuantumRange (1.0 / QuantumRange) |
| Transparent | Full transparency constant (0.0) |
Complete reference of built-in mathematical, utility, and control-flow functions:
| Function | Description & Formula |
|---|---|
| abs(x) | Absolute value of x. |
| acos(x), acosh(x) | Arc cosine and inverse hyperbolic cosine of x. |
| airy(x) | Airy function (max=1, min=0): [jinc(x)]² = [2*j1(pi*x)/(pi*x)]². |
| alt(x) | Sign alternation: returns 1.0 if int(x) is even, -1.0 if odd. |
| asin(x), asinh(x) | Arc sine and inverse hyperbolic sine of x. |
| atan(x), atanh(x) | Arc tangent and inverse hyperbolic tangent of x. |
| atan2(y, x) | Two-argument arc tangent of y/x. |
| ceil(x) | Smallest integral value not less than x. |
| channel(...) | Accepts 0–5 channel expressions; returns the value for the active channel and zeros omitted channels. |
| clamp(x) | Clamps x to the normalized [0.0, 1.0] range. |
| cos(x), cosh(x) | Cosine and hyperbolic cosine of x. |
| debug(x) | Prints x to stderr/stdout for expression debugging (forces single-threaded execution). |
| do(cond, stmts) | Executes stmts, then repeats while cond is non-zero. |
| drc(x, y) | Dynamic range compression (knee curve): x / (y*(x - 1) + 1) for -1 < y < 1. |
| epoch(date-time) | Converts a date-time property into seconds since the Unix epoch (00:00:00 UTC). |
| erf(x) | Gauss error function of x. |
| exp(x) | Natural exponential function (ex). |
| floor(x) | Largest integral value not greater than x. |
| for(init, cond, stmts) | Evaluates init, then iterates stmts while cond is non-zero. |
| gauss(x) | Gaussian function: exp(-x*x/2) / sqrt(2*pi). |
| gcd(x, y) | Greatest common divisor of x and y. |
| hypot(x, y) | Euclidean hypotenuse: sqrt(x² + y²). |
| if(cond, then, else) | Evaluates then if cond is non-zero, otherwise else. |
| int(x) | Greatest integer less than or equal to x. |
| isnan(x) | Returns 1.0 if x is NaN, otherwise 0.0. |
| j0(x), j1(x) | Bessel functions of the first kind of order 0 and order 1. |
| jinc(x) | Jinc function (max=1, min=-0.1323): 2*j1(pi*x)/(pi*x). |
| ln(x), log(x), logtwo(x) | Natural logarithm (base e), base-10 logarithm, and base-2 logarithm. |
| magicktime() | Current system time in seconds since the Unix epoch (00:00:00 UTC). |
| max(x, y), min(x, y) | Maximum or minimum of x and y. |
| mod(x, y) | Floating-point remainder of x divided by y. |
| not(x) | Returns 1.0 if x is zero, otherwise 0.0. |
| pow(x, y) | Power function (xy). |
| rand() | Uniform pseudo-random value in [0.0, 1.0) with a 2¹²⁸ - 1 period. |
| round(x) | Rounds x to the nearest integral value. |
| sign(x) | Returns -1.0 if x < 0.0, otherwise 1.0. |
| sin(x), sinh(x) | Sine and hyperbolic sine of x. |
| sinc(x) | Normalized sinc function (max=1, min=-0.21): sin(pi*x)/(pi*x). |
| sqrt(x) | Square root of x. |
| squish(x) | Logistic sigmoid function: 1.0 / (1.0 + exp(-x)). |
| tan(x), tanh(x) | Tangent and hyperbolic tangent of x. |
| trunc(x) | Truncates x to an integer toward zero. |
| while(cond, stmts) | Iterates stmts while cond is non-zero. |
Operator Precedence (Highest to Lowest)
- 1. Exponentiation: ^
- 2. Unary & Multiplicative: unary -, *, /, %
- 3. Additive & Bitwise Shift: +, -, <<, >>
- 4. Relational & Equality: <, <=, >, >=, ==, !=
- 5. Compound Assignment & Inc/Dec: +=, -=, *=, /=, %=, <<=, >>=, &=, |=, ++, --
- 6. Bitwise & Logical: &, |, &&, ||, ~ (logical NOT)
- 7. Ternary Conditional: ?:
- 8. Statement Assignment & Separator: =, ;
Operator Semantics & Boolean Rules
==, !=, <, <=, >, >=)1.0 when true and 0.0 when false. == and != compare values within Epsilon (1e-12).&&, ||, ~)x && y returns 1.0 if x > 0 and y > 0; x || y returns 1.0 if either > 0; ~x (logical NOT) returns 1.0 if not x > 0. Bitwise AND/OR use & and |.cond ? true-stmts : false-stmts)true-stmts if cond != 0, otherwise false-stmts. Only one ternary conditional is allowed per statement.if, for, while, do)if(cond, nonzero, zero), for(init, cond, stmts), while(cond, stmts), and do(cond, stmts) iterate while cond != 0.Syntax & Semantics Rules
- Case Insensitivity: Symbols and built-in identifiers are case insensitive.
- Statements & Assignments: Statements are separated by
;and consist of variable assignments or the final return expression. Assignment starts a statement—it is not an operator—and at most one ternary conditional (x ? y : z) is permitted per statement. - Variable Naming: Single-character names are reserved for built-ins; assigning to one throws an exception (e.g.,
r=3.0; rraises Attempted assignment to non-UserSymbol 'r'). Custom variables must use two or more letters only (e.g.,Xi, notX1). - Unary vs. Binary Precedence: Unary operators have lower precedence than exponentiation:
-3^2evaluates as-(3^2) = -9. Use parentheses ((-3)^2 = 9) to override. - Division & Implicit Multiplication:
1/2xis parsed as(1/2)x; write1/(2*x)explicitly when dividing by a product. - Subtracting Negative Numbers: Because
--is the decrement operator, wrap negative right-hand operands in parentheses:-4-(-5).
Source Images, Pixel Addressing & Channels
Image Sequence Indexes
u and v reference the first and second images in the sequence. Index any image reference with brackets (0-based; negative indexes count from the end; out-of-range indexes wrap around, so in a 3-image list u[-1], u[2], and u[5] all select the third image):
- u[0] First image
- u[2] Third image
- u[-1] Last image in list
- u[t] Current image (s)
Average the first and third images (the second image at index 1 is ignored and discarded):
Pixel & Neighborhood Access
All color values are normalized to 0.0–1.0 (alpha ranges from 0.0 transparent to 1.0 opaque). By default, p, r, g, b, and a read from s (equivalent to u except inside %[fx:...]).
Fractional coordinates return blended colors according to -interpolate, and out-of-bounds coordinates follow -virtual-pixel.
Channel Selection & Output Channels
Use -channel to choose which output channels -fx updates (by default, all channels except opacity are updated). Appending a channel qualifier such as u.r reads a specific input channel; omitting it reads the active channel. Use mean.this for the current channel's mean or mean.all for the overall mean across channels.
Replace the red channel of alpha.png with the average of the green channels from alpha.png and beta.png:
Because only the first image (u) is cloned and modified on the selected -channel green, blending a flopped logo with an unflopped logo produces an asymmetric result:
Results & Format Escapes
When -fx runs, computed channel values are written into a clone of u (s = u, t = 0), which then replaces the entire input image list. Instead of modifying image pixels, FX expressions can also be evaluated inside -format and -set string escapes:
%[fx:...] Value Escape
Evaluated once per image in the sequence (s and t step through each image, i = j = 0, channel defaults to red, and -channel is ignored).
-format 'Red channel of NW corner of image #%[fx:t] is %[fx:s] ' info:
Red channel of NW corner of image #0 is 0.464883
Red channel of NW corner of image #1 is 0.184582
%[pixel:...] & %[hex:...] Color Escapes
Evaluated once per image and per color channel (-channel ignored, i = j = 0), converting the resulting channel values into a named or hexadecimal color string.
Practical Escape Examples
Rotate each duplicated frame proportionally and set a longer animation pause on the first frame (t == 0):
-set delay '%[fx:t == 0 ? 240 : 10]' -loop 0 rose.gif
Compare two images with RMSE and return 1 if the distortion exceeds 0.1 (otherwise 0):
Convert an image modification date-time property into Unix epoch seconds using epoch():






