ImageMath
ImageMath evaluates expressions over single-band images. Python handles
expression syntax; Rust performs the pixel arithmetic, releasing the GIL and
using parallel execution for large buffers. No Pillow runtime dependency is
required.
from blanket import Image, ImageMath
image = Image.new("L", (64, 64), 80)
result = ImageMath.lambda_eval(
lambda args: args["convert"](args["a"] * 2 + 10, "L"),
a=image,
)
lambda_eval passes a dictionary to the callable containing the supplied
operands and the helpers int, float, convert, min, max, equal, and
notequal. Results can be images or ordinary Python values.
unsafe_eval("convert(a * 2 + 10, 'L')", a=image) accepts a Python expression
string. eval is a compatibility alias for unsafe_eval. Both use Python's
eval and must only receive trusted expressions and operands; name checks do
not make them a sandbox.
Operations and modes
Arithmetic accepts 1, L, I, and F images. 1 and L operands become
I; mixing integer and floating-point images produces F. Floating-point
constants used directly with integer images raise TypeError. Use float(a)
in an expression, or args["float"](args["a"]) in a callable, to request
floating-point arithmetic. Split multiband images before evaluating them.
Supported operators are unary +, -, abs, and ~; arithmetic +, -,
*, /, %, and **; bitwise &, |, ^, <<, and >>; and all six
comparisons. Bitwise operations require integer operands. Integer division
truncates toward zero; division and remainder by zero produce zero pixels.
Binary image operations use the top-left overlap when dimensions differ.
Comparisons return zero or one in the arithmetic result mode. The equal
and notequal helpers force I storage, including Pillow's float-bit storage
behavior for floating-point operands. Use int(a == b) to obtain an integer
zero-or-one mask from float comparisons.
Python and, or, and not use whole-image truth: an image is true when any
pixel is nonzero. They do not perform per-pixel logical operations. Input
images are not modified.
Reference
lambda_eval
lambda_eval(expression: Callable[[dict[str, Any]], Any], **operands: Any) -> Any
Evaluate a callable receiving a dictionary of images, values, and helpers.
Helpers are int, float, convert, min, max, equal, and notequal. Image arithmetic runs in Rust and returns I or F images. Use split and merge to process multiband images.
unsafe_eval
unsafe_eval(expression: str, **operands: Any) -> Any
Evaluate a trusted Python expression using native image arithmetic.
This calls Python eval and is not a sandbox for untrusted expressions or operands. Prefer lambda_eval for callable expressions.
eval
eval(expression: str, **operands: Any) -> Any
Compatibility alias for unsafe_eval; evaluate only trusted expressions.