Aner Image
Analyze typed still images with explicit coordinates, masks, region measurements, shared memory budgets and native model or plot adapters.
ImplementedAner 0.1.0 or neweraner.image is the native still image and quantitative pixel analysis module. Keep typed pixels, calibrated coordinates, masks and region measurements together, then connect the result to Tensor, neural models, machine learning or Plot.
Use a matching installed runtime and editor, and inspect the generated image API reference for exact signatures, defaults and return types.
Start with quantitative pixels
import aner.image
import aner.tensor
let work = image.context(workers: 1, memory_mb: 32)
let samples: Tensor = [[0.0, 5.0, 5.0, 0.0], [0.0, 5.0, 5.0, 0.0]]
let pixels = image.from_tensor(work, samples, dtype: "UInt16")
let regions = pixels.threshold(cutoff: 3.0).components(connectivity: 4).regions(pixels)
print(pixels.dtype())
print(regions.area(0))
print(regions.intensity_mean(0))This deterministic program prints UInt16 storage, four selected pixels and mean intensity five. It needs no file, camera, model weights or optional codec. The complete basic example also demonstrates strided views, deliberate copies and context counters.
Choose the right module
| Module | Responsibility |
|---|---|
aner.image | Typed immutable 2D images, geometry, filtering, masks, labels and quantitative measurements |
aner.video | Camera, file and network acquisition, frame timing, reusable capture slots and recording |
aner.vision | Explicit model input geometry and normalization, and postprocessing of supplied detection rows |
aner.tensor | Numerical model storage, explicit dtype/device conversion and tensor computation |
aner.signal | Sampled signal transforms and features; it does not reinterpret image coordinates |
aner.plot | Display snapshots and plots, with an explicit distinction between display mapping and measured pixels |
Image analysis runs on the local CPU. Transferring an exported tensor to an accelerator is an explicit model operation. The image module does not silently route a filter to a GPU or turn a display preview into calibrated measurement data.
A context owns the resource policy
Create one image context for an experiment or bounded processing batch. Reuse it for image construction, file loading and pipelines. Images retain their owning context; their operations use that same shared policy. A pipeline created with image.pipeline(context) also retains the context.
image.context(...) owns a reusable local worker pool. image.context_with(execution: parallel.local(...), ...) borrows an already selected native local executor. Neither route creates a new pool for each operation. Requested workers must fit the effective local CPU budget. A cluster context does not become an image executor.
One shared executor admits one active workload. Concurrent or nested submissions are rejected; the application must serialize submissions through contexts that share that pool. Immutable image values and an atomic byte ledger do not establish concurrent Executor.run support. Do not submit an image plan to a pool from inside another task already using that same pool.
The shared byte ledger charges retained image buffers and declared native workspace. Context copies share that ledger. Its live, peak and remaining byte counters describe the image ledger, not total process memory. Codec private allocations, allocator overhead, model weights, detached tensor storage and plot snapshots have their own lifetimes and costs.
Set a byte budget appropriate to the experiment and inspect peak usage on representative inputs. Also bound pixels, channels, component counts and working tiles. Admission failures are errors; they do not authorize an unbounded fallback or a smaller numerical type.
The language context accepts memory_mb from 1 through 4096, measured in MiB, and tile_rows from 1 through 4096. The component limit defaults to one million and may be set from 1 through ten million. The language context also retains fixed native limits of 100 million pixels and 64 channels. A small requested file region does not bypass full source geometry admission.
Pixel types, color and numerical meaning
| Storage | Meaning | Conversion boundary |
|---|---|---|
UInt8 | Unsigned integer samples, 0 through 255 | Reading or filtering does not imply normalization to 0 through 1 |
UInt16 | Unsigned integer samples, 0 through 65535 | High depth data stays high depth until an explicit conversion |
Int16 | Signed integer samples | Negative scientific values are retained |
Float32 | Native floating point samples | Floating TIFF and native buffer imports preserve NaN and infinity; analysis selects an invalid value policy |
Float64 | Native double precision samples | Preserve this type when the experiment requires its precision |
Channels are numeric unless their color metadata says otherwise. A channel count of three does not establish a color space. There is no implicit gamma correction, ICC transform, intensity normalization or camera calibration.
Select a channel deliberately for scalar analysis. Current Aner constructors support channel selection and numeric mean grayscale conversion. The native C++ implementation also supports Rec. 709 luminance from explicitly declared linear RGB, but current Aner constructors cannot declare that color space, so the Rec. 709 route is unavailable from Aner source. Encoded sRGB is not silently linearized. Alpha remains separate from measured intensity. Gray to RGB replication is an explicit one channel operation.
Nearest resize retains the input dtype. Linear resize and Gaussian filtering produce floating point output: Float64 input retains Float64; other input storage produces Float32. These operations calculate new samples rather than preserving an integer image byte for byte.
Casting is explicit. The default exact policy rejects unrepresentable range or precision changes. Round uses ties away from zero and still rejects out of range output; clamp explicitly rounds and clips. Creating a Float32 filled image rounds the supplied finite value to its requested storage type; integer fills reject fractions and range overflow. Scaling has an explicit factor, offset and output dtype. A display range is not an instruction to modify scientific pixels.
Immutable pixels and retained views
An Image is an immutable native value. Copies and aliases retain shared storage. A region crop and a channel selection are read only views; they can retain a parent row or pixel stride. Do not infer packed layout from width and channel count.
A small view can keep the entire source allocation alive. A deliberate image copy creates independent packed storage and temporarily requires both the retained source and the new destination to fit their budgets. Use a copy when independent ownership is useful, rather than copying every intermediate image automatically.
Avoid retaining every intermediate in a List. Hold the source needed for reproducibility and measurements, then retain only useful outputs. Check the shared context counters when processing a sequence of files or video frames. Inputs stay immutable when an operation fails; a failed pipeline must not be described as producing a new observation. Declared allocation reservations are released during failure cleanup, while references to previously completed outputs remain valid.
Pixel and physical coordinates
Coordinates are zero based. Integer (x, y) denotes a pixel center. Calibration maps pixel centers to physical coordinates:
physical = origin + direction * [spacing_x * x, spacing_y * y]Spacing must be finite and positive. Origin and direction must be finite; direction must be invertible. A calibration unit is a bounded descriptive label. It does not validate against the Aner units registry or perform a conversion automatically.
Use Aner units explicitly when a measured number needs a typed unit or conversion. First establish what the calibration label means and whether it matches the chosen registry unit. A label such as mm is provenance, not proof that an instrument was calibrated.
A crop shifts the physical origin to its first selected pixel. Resize uses the documented half pixel sampling map and adjusts origin and spacing. Flips and quarter turns update the coordinate transform as well as copying samples. Channel selection retains the spatial calibration.
Region centroids use pixel index centers; transform them with the image calibration when physical coordinates are required. A bounding box is (x, y, width, height). Region physical area is:
pixel_count * abs(det(direction)) * spacing_x * spacing_yIts dimensions are the square of the calibration unit. Pixel area and physical area are different measurements. Resampling, threshold choice and acquisition calibration can all change the scientific interpretation.
The current scalar unit registry can type a known coordinate such as units.quantity(x, "mm") and convert it to meters. It does not contain an area descriptor; keep physical area as a numerical value with its squared calibration label. Do not relabel area as a distance. See the complete physical coordinate example.
Invalid floating point samples
Floating TIFF and native buffer imports preserve NaN and infinity. Tensor adapters instead require finite samples and finite scaling results. Operations that analyze sample values expose reject and ignore policies; reject is the default. The selected channel, mask and operation determine which samples participate.
reject fails when an included sample is invalid. ignore excludes invalid samples from numerical support; it does not replace them with zero. Statistics report valid and invalid counts. A statistics or histogram mask must match both image dimensions and physical calibration. Variance is the population variance of valid selected samples, with denominator equal to that count. Empty selected support has count zero and sum zero; named numerical accessors reject undefined extrema or moments with R4501. Inspect the count before reading a mean, variance or standard deviation.
For an ignored invalid pixel, thresholding produces background rather than treating the intensity as zero. Gaussian filtering renormalizes valid weights in each separable pass; an output with no valid support remains NaN. Linear resize also needs an explicit invalid policy. Record this choice with the experiment, especially when missingness is spatially structured.
Filtering and geometry
Gaussian filtering is separable. Its radius is ceil(3 * sigma) with finite 0 < sigma <= 64. Supported borders are reflect, clamp and zero. Reflect uses the reflect 101 convention; a zero border represents a declared zero outside the image rather than measured support.
Use nearest resize for discrete samples when interpolation would invent categories. Masks and exact component labels are distinct native values, not intensity images to smooth or linearly resize. Apply a deliberate segmentation or label transformation when changing their geometry.
Use integer quarter turns and explicit horizontal or vertical flips for those exact geometric operations. Arbitrary angle interpolation, optical distortion correction, registration and camera calibration are separate future capabilities.
Masks, thresholds and exact labels
A mask stores foreground membership. Choose a scalar channel, a numerical cutoff and whether selection is above the cutoff. Default above selection is strictly greater than the cutoff. Histogram and Otsu analysis use an explicit numerical range and bin count; values outside that range are rejected rather than silently discarded.
Otsu chooses a threshold from the represented histogram. It does not learn an object class. When the declared histogram range is one constant intensity, Otsu returns that intensity; a strictly above comparison therefore yields no foreground. A wider declared range with only one occupied bin has no separable classes and is rejected. The numerical cutoff lies immediately below its selected upper bin boundary, so strict above selection includes values exactly on that boundary. Inspect these cases instead of assuming that every input contains a segmentable object.
Morphological dilation, erosion, opening and closing operate on masks with an explicit radius. Connected components use explicit four or eight connectivity. Background is zero; exact UInt32 labels are numbered by each component's first row major pixel. Retain exact labels rather than passing them through an imprecise display conversion.
The component budget is independent of the pixel budget. An image with many isolated foreground pixels can exhaust the component budget even when its pixel buffer fits. Failure does not produce a truncated set of components.
Region measurements need an explicit source
Region measurements can report pixel area, bounding box and centroid, and use the supplied image for intensity measurements. Keep the original intensity image when segmentation uses a smoothed, scaled or selected channel image. Measuring the filtered image answers a different question.
Pass the intended source image explicitly when asking a pipeline result for region measurements. Match geometry and select the intensity channel deliberately. Retain the region valid and invalid counts along with mean, minimum, maximum and sum.
Matching geometry alone does not identify the same observation. Keep source and session identity when measuring captured frames, and retain the calibration used to create the labels.
Reusable pipelines
An ImagePlan is an immutable sequence of analysis stages. image.pipeline(context) creates it; channel, gaussian, numerical threshold, automatic otsu and components compose the supported analysis. Each chained call returns a plan value and retains the same resource policy.
import aner.image
import aner.tensor
let work = image.context(workers: 1, memory_mb: 32)
let source = image.from_tensor(work, [[0.0, 0.0, 0.0],
[0.0, 8.0, 0.0], [0.0, 0.0, 0.0]])
let analysis = image.pipeline(work).channel(0).gaussian(sigma: 0.5).otsu().components()
let result = analysis.run(source)
print(result.labels().count())
print(result.regions(source).count())run(image) processes an already loaded image; the path overload opens the selected file explicitly. The result retains the produced image, mask and labels. Region intensity measurement remains a separate explicit choice of source image. A pipeline is not a trained model and does not establish a scientifically valid threshold for another dataset.
Partial plans are valid: run(...).image() returns their image output. Read a mask only after a threshold or Otsu stage, and read labels or region measurements only after components. An omitted stage is not an empty segmentation result.
Files and optional codecs
Inspect file headers before choosing the desired page, region and budget. Inspection identifies the supported container geometry and storage; it does not establish that every encoded input is valid. Decode errors remain possible.
| Format | Native numeric support | Availability and limits |
|---|---|---|
| Binary PNM | P5 grayscale and P6 RGB, UInt8 or UInt16 | Available without optional image codec libraries |
| PNG | UInt8 or UInt16 gray, gray with alpha, RGB and RGBA | Optional installed PNG library; noninterlaced input only; palettes and subbyte samples are unsupported |
| JPEG | UInt8 grayscale or RGB | Optional installed JPEG library; encoding is lossy and uses an explicit quality |
| TIFF | Supported contiguous stripped numeric images, including signed and floating point storage | Optional installed TIFF library; tiled input is unsupported; select page and region explicitly |
Inspect native capabilities and backend versions. A compiled codec does not imply support for every color model, compression, TIFF layout, page organization or vendor extension. Unsupported storage and conversions fail explicitly. Orientation and color profile correction are not applied automatically.
Region decoding retains the selected output plus a source scanline, but still scans the source rows for supported PNG, JPEG and TIFF input. Full source geometry and encoded file size must pass their limits. This is not arbitrary TIFF tile access or unbounded out of core processing. TIFF orientation and DPI are retained as source metadata; the raster is not rotated or resampled automatically. PNG gamma metadata does not alter decoded numeric samples. PNG export rejects premultiplied alpha until an explicit, verified conversion is supplied.
Writing refuses an existing destination. A failed new write removes the partial file it created. Use a fresh output path or directory for an example run. Float data does not silently become an 8 bit PNG or JPEG; select an explicit export conversion, or retain a supported scientific format.
import aner.image
let work = image.context(workers: 1, memory_mb: 32)
let pixels = image.create(work, width: 4, height: 3, dtype: "UInt16", value: 4096.0)
pixels.save("sample.pgm")
let header = image.inspect(work, "sample.pgm")
print(header.dtype())
print(header.pages())
print(image.load(work, "sample.pgm").sample(0, 0))Run this example in a fresh writable directory. PNM retains the integer samples, but its file format does not store the complete scientific calibration. Retain calibration and experiment provenance separately rather than assuming every image container preserves all metadata.
Decoded output and declared scanline or temporary buffers participate in the image context ledger. Decoder private allocation limits are codec specific. The image byte budget is not a hard limit on total process RSS.
Tensor, model and video bridges
Tensor exports are owned, detached copies with explicit Float32 or Float64 storage, layout, scale and offset. They require finite converted values and do not carry an autograd graph. Handle invalid image samples explicitly before model conversion. Choose HW for a single channel, HWC, CHW or NCHW to match the receiving operation. FLAT export produces [1, height * width * channels] in HWC order for an explicitly arranged feature row. A shape alone does not establish a correct color space or normalization.
The image context reserves export workspace while allocating the tensor. Once the neural tensor owns its buffer, that retained memory belongs to neural storage accounting rather than the image ledger. Retained tensors, device transfers and model parameters require their own budgets. Tensor import creates an image owned by the selected image context; integer output requires an explicit representable conversion. Import needs a spatial layout that supplies the image geometry rather than guessing dimensions from a flat row.
import aner.image
import aner.tensor
let work = image.context(workers: 1, memory_mb: 32)
let pixels = image.create(work, width: 16, height: 12, channels: 3,
dtype: "UInt16", value: 1024.0)
let batch = pixels.tensor(dtype: "Float32", layout: "NCHW", scale: 1.0 / 65535.0)
print(tensor.dim(batch, 0))
print(tensor.dim(batch, 1))This declares numerical scaling for UInt16 samples. It does not declare a color transform or show that this preprocessing matches a trained model. The complete bridge example combines a synthetic video frame, owned image, Vision preprocessing, a random CNN, a trivial ML self query and a plot snapshot.
Use aner.nn for image model execution and aner.ml for explicitly arranged features or region measurements. Do not treat a random untrained model as an object recognizer. Fit preprocessing on training observations, preserve held out populations and retain the transformation recipe with the model.
Importing a video frame creates an owned image copy and retains the available source, session, sequence and timing provenance. It does not borrow a mutable capture slot that the next read will overwrite. The existing RGB8 capture boundary remains RGB8; it cannot recover precision absent from a camera frame.
For several sources, pull bounded frames fairly, process them with the selected shared analysis context and retain only useful outputs. Serialize submissions to that executor instead of creating an unbounded set of analysis threads for each camera or frame. A loop local binding can retain its latest native image or slot until the function or session cell ends; iteration completion is not a guarantee that the latest handle was released. Reuse slots and bound retained images, tensors and model results.
The typed vision.prepare_into(plan, frame, input) overload accepts an Image through the same existing Vision plan. Its parameter remains named frame for compatibility with the frame overloads. It accepts the five image storage types, requires exactly three channels and produces finite Float32 model input. Select channels or replicate gray explicitly, and choose normalization for the numerical range and color meaning of the source. The default Vision scale used for RGB8 capture does not establish a suitable scale for another image range.
Display is a separate operation
image.plot(...) creates a bounded native plot snapshot from one numeric channel or an explicitly selected three channel image. Choose a display low and high range explicitly. The preview maps pixels to a PNG raster for visualization and may use a smaller nearest sampled thumbnail. Invalid samples are shown in magenta. mask_plot and label_plot add typed overlays as a display choice; the original scientific pixels and exact labels are retained separately. Select channels explicitly before displaying alpha or other multichannel data.
Preview encoding uses the native plot raster path and does not require the optional PNG file codec. Its compression workspace is charged to the image context; the resulting chart snapshot has its own retained memory. A display PNG is not a replacement for signed, high depth or floating point source data.
This figure is the actual bounded raster output of the bridge example. It represents synthetic pixel values, not detected objects or an accuracy result.
Performance and reproducibility
Reuse a context, worker pool and pipeline. Choose the source resolution and channels needed by the analysis. Prefer a view when shared retention is appropriate and an explicit copy when independent ownership is needed. Keep image and tensor transfers visible in the experiment.
Parallelism follows the operation phase rather than every method call:
| Phase | Execution |
|---|---|
| Crop, channel and calibration views | Serial metadata operations without pixel copies |
| Pixel copies, casts, scaling, geometry, grayscale, Gaussian passes, thresholds and morphology | Native row work through the selected local executor; small work can run serially |
| Statistics | Fixed row tiles, default 32 rows, followed by a serial fixed order Welford merge |
| Histograms | Native row partitions followed by an exact serial UInt64 bin merge |
| Connected components | Serial union and canonical label discovery, then parallel pixel relabeling |
| Region measurements | Serial scan and finalization |
| Automatic Otsu | Statistics and histogram work can use workers; optimizing across histogram bins is serial |
| Large image and Tensor conversions, typed Image to Vision preparation | Reuse the context row executor; no bridge speed claim is established by the pipeline measurement below |
| File codecs and PNG encoding | Serial codec work |
Record tile_rows with a numerical replay recipe. Fixed tile boundaries and merge order are part of the statistics calculation; changing a reduction partition can change floating point rounding even when the underlying samples are unchanged.
Measure the complete workload as well as individual stages. Record input dimensions, dtype, channels, strides, calibration, invalid policy, kernel or threshold settings, connectivity, worker policy, byte budget, retained aliases and optional backend versions. Report elapsed time and throughput alongside context peak bytes and process memory. Warm and cold file or model paths answer different questions.
Use several repeated trials on the actual hardware and verify numerical outputs before comparing speed. A worker count, SIMD build flag or cached input does not establish a speedup. GPU image kernels, zero copy shared capture surfaces, 3D volumes, automatic registration and advanced morphology are future work.
Recorded native compute workload
The measurement receipt records a deterministic one channel UInt16 image passed through Gaussian filtering with sigma one, manual threshold 25000 and labeling with connectivity eight. This is a source measurement on one Apple M2 Max with 64 GB memory and 12 CPU cores. The Release build used Apple clang 21, -O3, an Apple M1 CPU target, strict floating point flags and no LTO.
Recorded source hashes identify the exact uncommitted development snapshot measured, including its image kernels and benchmark driver. The timings remain measurements of that snapshot when later source corrections are made.
| Image | Local workers | Serial median | Parallel median | Observed ratio |
|---|---|---|---|---|
| 1024 × 1024 | 2 | 44.71 ms | 24.88 ms | 1.80× |
| 2048 × 2048 | 4 | 178.72 ms | 56.93 ms | 3.14× |
Each measurement used one warmup and five timed repetitions with a reusable plan. The timer covers native pipeline computation; fixture creation, file codecs, checksums, output destruction and model inference are excluded. Serial and parallel component counts and label checksums agreed. Raw individual timing samples were not retained, so the table does not describe a timing distribution.
The receipt also records context peak owned and reserved bytes. Those counters are not process RSS, and the table does not establish a performance guarantee for another image, machine, build or published package. Automatic Otsu analysis is available in the API but was not part of this manual threshold timing workload.
Examples and validation
- Basic typed pixels and views.
- Masks, exact labels and region measurements.
- Physical coordinates and explicit units.
- A reusable bounded pipeline.
- File inspection and a native PNM round trip.
- Tensor, video, vision and plot bridges.
Checking a program validates source syntax, types and argument names. It does not open an input file, allocate a pixel image, run a codec or perform a model calculation. Image runtime failures use source located R4501 diagnostics; bridges retain the diagnostic contract of their owning module. These APIs execute through the native runtime interpreter; the standalone typed CPU source compiler does not lower image programs.
Runtime tests and measured examples establish only their recorded inputs, builds and hardware; they do not qualify an arbitrary camera or scientific instrument.
See the complete callable index for the native module and method name catalogue.