nk 1.0.0
C++ Numerical Computing Runtime
Loading...
Searching...
No Matches
Image Processing Toolbox (image)

Color space conversions, morphological operations, 2D spatial filtering, geometric transformations, and quality metrics (SSIM, PSNR). More...

Files

file  arithmetic.hpp
file  color.hpp
 Colour-space conversions, Lab helpers, colormaps.
file  contrast.hpp
file  filter.hpp
file  geom.hpp
file  io.hpp
file  morph.hpp
 Morphological operations (function-form).
file  object.hpp
file  quality.hpp
file  region.hpp
file  segment.hpp
file  texture.hpp
file  transform.hpp
file  type_convert.hpp
 Image type-conversion helpers.

Classes

struct  nk::image::AdaptHistEqOptions
 Parameters for adapthisteq. More...
struct  nk::image::DeconvregResult
 Result of regularized deconvolution ([J, LAGRA] = deconvreg(...)). More...

Enumerations

enum class  nk::image::PadMode { PadMode::Constant , PadMode::Replicate , PadMode::Symmetric , PadMode::Circular }
 Boundary handling for image filtering / padding. More...

Functions

Value nk::image::imadd (const Value &x, const Value &y, std::pmr::memory_resource *mr=nullptr)
 Saturating image addition (Z = imadd(X, Y)).
Value nk::image::imsubtract (const Value &x, const Value &y, std::pmr::memory_resource *mr=nullptr)
 Saturating image subtraction (Z = imsubtract(X, Y)).
Value nk::image::immultiply (const Value &x, const Value &y, std::pmr::memory_resource *mr=nullptr)
 Saturating element-wise multiplication (Z = immultiply(X, Y)).
Value nk::image::imdivide (const Value &x, const Value &y, std::pmr::memory_resource *mr=nullptr)
 Saturating element-wise division (Z = imdivide(X, Y)).
Value nk::image::imabsdiff (const Value &x, const Value &y, std::pmr::memory_resource *mr=nullptr)
 Saturating absolute difference (Z = imabsdiff(X, Y)).
Value nk::image::imcomplement (const Value &x, std::pmr::memory_resource *mr=nullptr)
 Image complement (Y = imcomplement(X)).
Value nk::image::imlincomb (const std::vector< double > &coefs, const std::vector< Value > &images, ValueType output_class, std::pmr::memory_resource *mr=nullptr)
 Linear combination of images (Z = imlincomb(coefs, images, class)).
Value nk::image::imapplymatrix (const Value &M, const Value &x, ValueType output_class, std::pmr::memory_resource *mr=nullptr)
 Apply a colour-space transform matrix (Y = imapplymatrix(M, X)).
void nk::image::imsplit (const Value &I, std::vector< Value > &planes, std::pmr::memory_resource *mr=nullptr)
 Split a multi-plane image into per-plane Values (imsplit(I, planes)).
Value nk::image::rgb2hsv (const Value &x, std::pmr::memory_resource *mr=nullptr)
 RGB → HSV (hsv = rgb2hsv(rgb)).
Value nk::image::hsv2rgb (const Value &x, std::pmr::memory_resource *mr=nullptr)
 HSV → RGB (inverse of rgb2hsv).
Value nk::image::rgb2ycbcr (const Value &x, std::pmr::memory_resource *mr=nullptr)
 RGB → YCbCr (BT.601) (ycbcr = rgb2ycbcr(rgb)).
Value nk::image::ycbcr2rgb (const Value &x, std::pmr::memory_resource *mr=nullptr)
 YCbCr → RGB (inverse of rgb2ycbcr).
Value nk::image::rgb2ntsc (const Value &x, std::pmr::memory_resource *mr=nullptr)
 RGB → NTSC YIQ (yiq = rgb2ntsc(rgb)).
Value nk::image::ntsc2rgb (const Value &x, std::pmr::memory_resource *mr=nullptr)
 NTSC YIQ → RGB (inverse of rgb2ntsc).
Value nk::image::rgb2xyz (const Value &x, std::pmr::memory_resource *mr=nullptr)
 sRGB → CIE XYZ (D65) (xyz = rgb2xyz(rgb)).
Value nk::image::xyz2rgb (const Value &x, std::pmr::memory_resource *mr=nullptr)
 CIE XYZ → sRGB (inverse of rgb2xyz).
Value nk::image::rgb2lab (const Value &x, std::pmr::memory_resource *mr=nullptr)
 sRGB → CIE L*a*b* (D65) (lab = rgb2lab(rgb)).
Value nk::image::lab2rgb (const Value &x, std::pmr::memory_resource *mr=nullptr)
 CIE L*a*b* → sRGB (inverse of rgb2lab).
Value nk::image::rgb2lightness (const Value &RGB, std::pmr::memory_resource *mr=nullptr)
 Lightness L* (L = rgb2lightness(RGB)).
std::pair< Value, Value > nk::image::cmunique_xm (const Value &X, const Value &MAP, std::pmr::memory_resource *mr=nullptr)
 Eliminate duplicate colors in colormap; convert grayscale or RGB to indexed ([Y, newmap] = cmunique(...)).
std::pair< Value, Value > nk::image::cmunique_rgb (const Value &RGB, std::pmr::memory_resource *mr=nullptr)
std::pair< Value, Value > nk::image::cmunique_i (const Value &I, std::pmr::memory_resource *mr=nullptr)
std::pair< Value, Value > nk::image::rgb2ind_inmap (const Value &RGB, const Value &cmap, std::pmr::memory_resource *mr=nullptr)
 RGB → indexed image with a fixed colormap ([ind, cmap] = rgb2ind(RGB, cmap)).
Value nk::image::xyz2lab (const Value &x, std::pmr::memory_resource *mr=nullptr)
 CIE XYZ → CIE L*a*b* (D50 ICC reference white).
Value nk::image::lab2xyz (const Value &x, std::pmr::memory_resource *mr=nullptr)
 CIE L*a*b* → CIE XYZ (inverse of xyz2lab).
Value nk::image::lab2double (const Value &lab, std::pmr::memory_resource *mr=nullptr)
 Cast Lab image to DOUBLE (labd = lab2double(lab)).
Value nk::image::lab2single (const Value &lab, std::pmr::memory_resource *mr=nullptr)
 Cast Lab image to SINGLE (labs = lab2single(lab)).
Value nk::image::lab2uint8 (const Value &lab, std::pmr::memory_resource *mr=nullptr)
 Cast Lab image to UINT8 (labu = lab2uint8(lab)).
Value nk::image::lab2uint16 (const Value &lab, std::pmr::memory_resource *mr=nullptr)
 Cast Lab image to UINT16 (labu = lab2uint16(lab)).
Value nk::image::colorgradient (const Value &C, const Value &w, int n, std::pmr::memory_resource *mr=nullptr)
 Smooth colormap through K anchor colours (M = colorgradient(C, w, n)).
Value nk::image::wavelength2rgb (const Value &wavelength, const std::string &out_class, double gamma, std::pmr::memory_resource *mr=nullptr)
 Wavelength → RGB (Bruton 1996) (RGB = wavelength2rgb(wavelength, class, gamma)).
Value nk::image::colorangle (const Value &rgb1, const Value &rgb2, std::pmr::memory_resource *mr=nullptr)
 Angle between two RGB colours (theta = colorangle(rgb1, rgb2)).
Value nk::image::gray_cmap (int n, std::pmr::memory_resource *mr=nullptr)
 Grayscale colormap (map = gray(n)).
Value nk::image::hot_cmap (int n, std::pmr::memory_resource *mr=nullptr)
 Black-red-yellow-white colormap (map = hot(n)).
Value nk::image::cool_cmap (int n, std::pmr::memory_resource *mr=nullptr)
 Cyan → magenta colormap (map = cool(n)).
Value nk::image::spring_cmap (int n, std::pmr::memory_resource *mr=nullptr)
 Magenta → yellow colormap (map = spring(n)).
Value nk::image::summer_cmap (int n, std::pmr::memory_resource *mr=nullptr)
 Green → yellow colormap (map = summer(n)).
Value nk::image::autumn_cmap (int n, std::pmr::memory_resource *mr=nullptr)
 Red → yellow colormap (map = autumn(n)).
Value nk::image::winter_cmap (int n, std::pmr::memory_resource *mr=nullptr)
 Blue → cyan-ish colormap (map = winter(n)).
Value nk::image::copper_cmap (int n, std::pmr::memory_resource *mr=nullptr)
 Copper-tinted colormap (map = copper(n)).
Value nk::image::pink_cmap (int n, std::pmr::memory_resource *mr=nullptr)
 Pastel-pink colormap (map = pink(n)).
Value nk::image::hsv_cmap (int n, std::pmr::memory_resource *mr=nullptr)
 Hue-rotation colormap (map = hsv(n)).
Value nk::image::flag_cmap (int n, std::pmr::memory_resource *mr=nullptr)
 Cyclic red/white/blue/black colormap (map = flag(n)).
Value nk::image::prism_cmap (int n, std::pmr::memory_resource *mr=nullptr)
 Cyclic 6-row rainbow palette (map = prism(n)).
Value nk::image::lines_cmap (int n, std::pmr::memory_resource *mr=nullptr)
 Axes-color-order palette (map = lines(n)).
Value nk::image::bone_cmap (int n, std::pmr::memory_resource *mr=nullptr)
 Grayscale-with-blue-tint colormap (map = bone(n)).
Value nk::image::white_cmap (int n, std::pmr::memory_resource *mr=nullptr)
 All-ones colormap (map = white(n)).
Value nk::image::rgb2lin (const Value &A, std::pmr::memory_resource *mr=nullptr)
 sRGB → linear RGB gamma inverse (B = rgb2lin(A)).
Value nk::image::lin2rgb (const Value &A, std::pmr::memory_resource *mr=nullptr)
 Linear RGB → sRGB gamma forward (B = lin2rgb(A)).
Value nk::image::xyz2double (const Value &xyz, std::pmr::memory_resource *mr=nullptr)
 XYZ → DOUBLE (xyzd = xyz2double(xyz)).
Value nk::image::xyz2uint16 (const Value &xyz, std::pmr::memory_resource *mr=nullptr)
 XYZ → UINT16 ICC encoding (xyzu16 = xyz2uint16(xyz)).
Value nk::image::brighten (const Value &map, double beta, std::pmr::memory_resource *mr=nullptr)
 Gamma-adjust a colormap (rmap = brighten(map, beta)).
Value nk::image::contrast (const Value &x, int m, std::pmr::memory_resource *mr=nullptr)
 Histogram-equalising gray colormap (cmap = contrast(x, m)).
Value nk::image::rgbwide2ycbcr (const Value &RGB, int bits_per_sample, std::pmr::memory_resource *mr=nullptr)
 BT.2020 / BT.2100 wide-gamut RGB → YCbCr (ycbcr = rgbwide2ycbcr(RGB, bps)).
Value nk::image::ycbcr2rgbwide (const Value &YCBCR, int bits_per_sample, std::pmr::memory_resource *mr=nullptr)
 BT.2020 / BT.2100 wide-gamut YCbCr → RGB (rgb = ycbcr2rgbwide(YCBCR, bps)).
Value nk::image::imcolordiff (const Value &I1, const Value &I2, const std::string &standard, bool is_input_lab, double kL, double kC, double kH, double K1, double K2, std::pmr::memory_resource *mr=nullptr)
 CIE94 / CIEDE2000 colour difference (dE = imcolordiff(I1, I2, ...)).
Value nk::image::deltaE (const Value &I1, const Value &I2, bool isInputLab, std::pmr::memory_resource *mr=nullptr)
 CIE76 colour difference (delE = deltaE(I1, I2, isInputLab)).
Value nk::image::whitepoint (const std::string &illuminant, std::pmr::memory_resource *mr=nullptr)
 CIE reference-illuminant tristimulus (wp = whitepoint(illuminant)).
Value nk::image::cmap2gray (const Value &cmap, std::pmr::memory_resource *mr=nullptr)
 RGB colormap → grayscale colormap (gmap = cmap2gray(cmap)).
Value nk::image::illumwhite (const Value &A, double P, const Value &mask, std::pmr::memory_resource *mr=nullptr)
 White-Patch illuminant estimate (illum = illumwhite(A [, P] [, 'Mask', M])).
Value nk::image::illumpca (const Value &A, double P, const Value &mask, std::pmr::memory_resource *mr=nullptr)
 PCA-based illuminant estimate (illum = illumpca(A [, P] [, 'Mask', M])).
Value nk::image::illumgray (const Value &A, const std::vector< double > &P, const Value &mask, std::pmr::memory_resource *mr=nullptr)
 Grey-World illuminant estimate (illum = illumgray(A [, P] [, 'Mask', M])).
Value nk::image::label2rgb (const Value &L, const Value &cmap, const Value &background, std::pmr::memory_resource *mr=nullptr)
 Colourise a labelled image (RGB = label2rgb(L, cmap, background)).
Value nk::image::imfuse (const Value &A, const Value &B, const std::string &method, const std::string &scaling, const Value &channels, std::pmr::memory_resource *mr=nullptr)
 Composite two images for visual comparison (C = imfuse(A, B, method, ...)).
Value nk::image::tonemap (const Value &HDR, double lremap_lo, double lremap_hi, double saturation, int ntilesR, int ntilesC, std::pmr::memory_resource *mr=nullptr)
 Render high-dynamic-range image for low-dynamic-range display (RGB = tonemap(HDR, ...)).
Value nk::image::labeloverlay (const Value &A, const Value &L, const Value &colormap, const std::string &color_assignment, const Value &included_labels, double transparency, std::pmr::memory_resource *mr=nullptr)
 Overlay a label / mask / categorical-index image on a 2-D base (B = labeloverlay(A, L, ...)).
Value nk::image::chromadapt (const Value &A, const Value &illuminant, const std::string &method, const std::string &color_space, std::pmr::memory_resource *mr=nullptr)
 Chromatic adaptation for white-balance correction (B = chromadapt(A, illuminant, ...)).
Value nk::image::rgbwide2xyz (const Value &RGB, int bits_per_sample, const std::string &color_space, const std::string &linearization, std::pmr::memory_resource *mr=nullptr)
 Narrow-range wide-gamut RGB → CIE 1931 XYZ (XYZ = rgbwide2xyz(RGB, BPS, ...)).
Value nk::image::xyz2rgbwide (const Value &XYZ, int bits_per_sample, const std::string &color_space, const std::string &linearization, std::pmr::memory_resource *mr=nullptr)
 CIE 1931 XYZ → narrow-range wide-gamut RGB (RGB = xyz2rgbwide(XYZ, BPS, ...)).
Value nk::image::demosaic (const Value &I, const std::string &sensorAlignment, int bitsPerSample=0, std::pmr::memory_resource *mr=nullptr)
 Convert a Bayer-encoded mosaic to a truecolor RGB image (RGB = demosaic(I, sensorAlignment, BitsPerSample=bps)).
Value nk::image::raw2planar (const Value &cfa, std::pmr::memory_resource *mr=nullptr)
 Deinterleave a Bayer CFA mosaic into its four sensor planes (P = raw2planar(cfa)).
Value nk::image::planar2raw (const Value &I, std::pmr::memory_resource *mr=nullptr)
 Re-interleave 4 sensor planes into a full Bayer CFA mosaic (cfa = planar2raw(I)).
std::tuple< Value, Value > nk::image::imhist (const Value &I, int n, std::pmr::memory_resource *mr=nullptr)
 Image histogram ([counts, bin_centers] = imhist(I, n)).
Value nk::image::stretchlim (const Value &I, double low_tol, double high_tol, std::pmr::memory_resource *mr=nullptr)
 Stretch limits from saturation tolerances (lim = stretchlim(I, [low_tol, high_tol])).
Value nk::image::imadjust (const Value &I, double low_in, double high_in, double low_out, double high_out, double gamma, std::pmr::memory_resource *mr=nullptr)
 Affine intensity remap with optional gamma (J = imadjust(...)).
Value nk::image::adaptthresh (const Value &I, double sensitivity, int neighborhood, const std::string &statistic, std::pmr::memory_resource *mr=nullptr)
 Locally adaptive threshold matrix (T = adaptthresh(I, ...)).
Value nk::image::histeq (const Value &I, int n, std::pmr::memory_resource *mr=nullptr)
 Histogram equalisation (J = histeq(I, n)).
Value nk::image::adapthisteq (const Value &I, const AdaptHistEqOptions &opts={}, std::pmr::memory_resource *mr=nullptr)
 Contrast Limited Adaptive Histogram Equalisation (J = adapthisteq(I, opts)).
std::tuple< Value, Value > nk::image::graythresh (const Value &I, std::pmr::memory_resource *mr=nullptr)
 Otsu's threshold and effectiveness metric ([level, em] = graythresh(I)).
std::tuple< Value, Value > nk::image::otsuthresh (const Value &counts, std::pmr::memory_resource *mr=nullptr)
 Otsu's threshold from a precomputed histogram ([level, em] = otsuthresh(counts)).
std::tuple< Value, Value > nk::image::multithresh (const Value &I, int N, std::pmr::memory_resource *mr=nullptr)
 N-level Otsu ([thresh, em] = multithresh(I, N)).
Value nk::image::imbinarize (const Value &I, double thresh, std::pmr::memory_resource *mr=nullptr)
 Threshold an image (BW = imbinarize(I, thresh)).
Value nk::image::imbinarize (const Value &I, const Value &T, std::pmr::memory_resource *mr=nullptr)
 Per-pixel threshold (BW = imbinarize(I, T)).
Value nk::image::imquantize (const Value &I, const Value &levels, std::pmr::memory_resource *mr=nullptr)
 Quantise into N+1 classes (L = imquantize(I, levels)).
Value nk::image::imhistmatch (const Value &I, const Value &ref, int nbins, Value *hgramOut=nullptr, std::pmr::memory_resource *mr=nullptr)
 Histogram matching to a reference image ([J, hgram] = imhistmatch(I, ref, nbins)).
Value nk::image::imflatfield (const Value &I, double sigma, const Value &mask, std::pmr::memory_resource *mr=nullptr)
 Flat-field correction (J = imflatfield(I, sigma, mask)).
Value nk::image::wcodemat (const Value &X, int nb, const std::string &opt, int absol, std::pmr::memory_resource *mr=nullptr)
 Wavelet-display quantisation (Y = wcodemat(X, nb, opt, absol)).
Value nk::image::entropy (const Value &I, int nbins, std::pmr::memory_resource *mr=nullptr)
 Shannon entropy of the image histogram (H = entropy(I, nbins)).
Value nk::image::grayslice (const Value &I, int N, std::pmr::memory_resource *mr=nullptr)
 Multilevel thresholding into an indexed image, level-count form (L = grayslice(I, N)).
Value nk::image::grayslice (const Value &I, Span< const double > levels, std::pmr::memory_resource *mr=nullptr)
 Multilevel thresholding into an indexed image, explicit thresholds form (L = grayslice(I, [t1, t2, …])).
Value nk::image::padarray (const Value &x, const std::vector< int > &padsize, PadMode mode, double pad_value, const std::string &direction, std::pmr::memory_resource *mr=nullptr)
 Pad an array by padsize elements on each side (B = padarray(A, padsize, mode, val, dir)).
Value nk::image::fspecial (const std::string &type, const std::vector< double > &params, std::pmr::memory_resource *mr=nullptr)
 Build a 2-D filter kernel by name (h = fspecial(type, params)).
Value nk::image::fspecial3 (const std::string &type, const Value &a1, const Value &a2, std::pmr::memory_resource *mr=nullptr)
 Build a predefined 3-D filter kernel (h = fspecial3(type, ...)).
Value nk::image::imfilter (const Value &I, const Value &h, PadMode boundary, double pad_value, bool full, bool flip_kernel, std::pmr::memory_resource *mr=nullptr)
 2-D linear filtering (B = imfilter(I, h, ...)).
Value nk::image::imgaussfilt (const Value &I, double sigma, int filter_size, std::pmr::memory_resource *mr=nullptr)
 2-D Gaussian filter (B = imgaussfilt(I, sigma, filter_size)).
Value nk::image::imboxfilt (const Value &I, int filter_size, std::pmr::memory_resource *mr=nullptr)
 2-D box / mean filter (B = imboxfilt(I, filter_size)).
Value nk::image::integralBoxFilter (const Value &I, int fH, int fW, double normFactor, std::pmr::memory_resource *mr=nullptr)
 2-D box filter on a precomputed integral image (B = integralBoxFilter(I, [fH fW], normFactor)).
Value nk::image::integralBoxFilter3 (const Value &I, int fH, int fW, int fP, double normFactor, std::pmr::memory_resource *mr=nullptr)
 3-D box filter on a precomputed integral volume (B = integralBoxFilter3(A, [fH fW fP], NormalizationFactor, n)).
Value nk::image::modefilt (const Value &A, int fH, int fW, const std::string &padopt, std::pmr::memory_resource *mr=nullptr)
 2-D mode filter (B = modefilt(A, [fH fW], padopt)).
Value nk::image::modefilt3D (const Value &A, int fH, int fW, int fD, const std::string &padopt, std::pmr::memory_resource *mr=nullptr)
 3-D variant: modefilt(V, [fH fW fD], padopt).
Value nk::image::roifilt2 (const Value &h, const Value &I, const Value &BW, std::pmr::memory_resource *mr=nullptr)
 Filter a region of interest (J = roifilt2(h, I, BW)).
Value nk::image::imguidedfilter (const Value &A, const Value &G, int nhood, double eps, std::pmr::memory_resource *mr=nullptr)
 Edge-preserving guided filter (B = imguidedfilter(A, G, ...)).
Value nk::image::imdiffusefilt (const Value &I, const Value &thresh, std::size_t N, const std::string &connectivity, const std::string &conduction, std::pmr::memory_resource *mr=nullptr)
 Anisotropic-diffusion edge-preserving smoothing (B = imdiffusefilt(I, ...)).
void nk::image::imgaborfilt (const Value &A, double wavelength, double orientation, double sfb, double aspect, Value &mag_out, Value &phase_out, std::pmr::memory_resource *mr=nullptr)
 Apply a single Gabor filter to a 2-D image ([mag, phase] = imgaborfilt(A, wavelength, orientation, ...)).
void nk::image::imnlmfilt (const Value &I, double dos, int swsize, int cwsize, Value &J_out, double &est_out, std::pmr::memory_resource *mr=nullptr)
 Non-local means denoising ([J, estDoS] = imnlmfilt(I, ...)).
Value nk::image::medfilt2 (const Value &I, int rows=3, int cols=3, std::pmr::memory_resource *mr=nullptr)
 2-D median filter (B = medfilt2(I, [m n])).
Value nk::image::imsharpen (const Value &I, double radius, double amount, double threshold, std::pmr::memory_resource *mr=nullptr)
 Unsharp masking (B = imsharpen(I, radius, amount, threshold)).
Value nk::image::im2col (const Value &A, int m, int n, const std::string &block_type, std::pmr::memory_resource *mr=nullptr)
 Rearrange image neighbourhoods into matrix columns (B = im2col(A, [m n], block_type)).
Value nk::image::col2im (const Value &B, int m, int n, int mm, int nn, const std::string &block_type, std::pmr::memory_resource *mr=nullptr)
 Inverse of im2col (A = col2im(B, [m n], [mm nn], block_type)).
Value nk::image::imbilatfilt (const Value &I, double degreeOfSmoothing, double spatialSigma, std::pmr::memory_resource *mr=nullptr)
 Edge-preserving bilateral filter (B = imbilatfilt(I, degreeOfSmoothing, spatialSigma)).
Value nk::image::imnoise (::nk::ops::RngContext &rng, const Value &I, const std::string &mode, const Value &p1, const Value &p2, std::pmr::memory_resource *mr=nullptr)
 Add synthetic noise to an image (J = imnoise(I, mode, p1, p2)).
Value nk::image::stdfilt (const Value &I, const Value &domain, std::pmr::memory_resource *mr=nullptr)
 Local sample standard deviation (B = stdfilt(I, domain)).
Value nk::image::rangefilt (const Value &I, const Value &domain, std::pmr::memory_resource *mr=nullptr)
 Local max − min over a neighbourhood (B = rangefilt(I, domain)).
Value nk::image::imsmooth (const Value &I, const std::string &name, double sigma, std::pmr::memory_resource *mr=nullptr)
 Octave-image style smoothing dispatcher (J = imsmooth(I, name, sigma)).
Value nk::image::imboxfilt3 (const Value &V, int fH, int fW, int fP, std::pmr::memory_resource *mr=nullptr)
 3-D box (mean) filter (J = imboxfilt3(V, fH, fW, fP)).
Value nk::image::convmtx2 (const Value &h, int m, int n, std::pmr::memory_resource *mr=nullptr)
 2-D convolution matrix (T = convmtx2(h, m, n)).
Value nk::image::imgaussfilt3 (const Value &V, double sigH, double sigW, double sigP, std::pmr::memory_resource *mr=nullptr)
 3-D Gaussian filter (J = imgaussfilt3(V, sigH, sigW, sigP)).
Value nk::image::medfilt3 (const Value &V, int M, int N, int P, std::pmr::memory_resource *mr=nullptr)
 3-D median filter (J = medfilt3(V, [M N P])).
Value nk::image::entropyfilt (const Value &I, const Value &domain, std::pmr::memory_resource *mr=nullptr)
 Local Shannon entropy (B = entropyfilt(I, domain)).
Value nk::image::ordfilt2 (const Value &A, int nth, const Value &domain, const Value &S, PadMode boundary, double pad_value, std::pmr::memory_resource *mr=nullptr)
 2-D order-statistic filter (B = ordfilt2(A, nth, domain, S)).
std::tuple< Value, Value, Value > nk::image::freqz2 (const Value &h, size_t M, size_t N, std::pmr::memory_resource *mr=nullptr)
 2-D frequency response of a filter ([H, f1, f2] = freqz2(h, M, N)).
std::tuple< Value, Value > nk::image::wiener2 (const Value &I, size_t nh, size_t nw, double noise, std::pmr::memory_resource *mr=nullptr)
 Adaptive Wiener noise reduction ([J, noise] = wiener2(I, nh, nw, noise)).
Value nk::image::nlfilter (const Value &A, std::size_t m, std::size_t n, FnHandle fun, bool indexed, std::pmr::memory_resource *mr=nullptr)
 General sliding-neighbourhood operation (B = nlfilter(A, [m n], fun)).
Value nk::image::colfilt (const Value &A, std::size_t m, std::size_t n, const std::string &block_type, FnHandle fun, bool indexed, std::pmr::memory_resource *mr=nullptr)
 Column-wise neighbourhood operation (B = colfilt(A, [m n], block_type, fun)).
Value nk::image::locallapfilt (const Value &I, double sigma, double alpha, double beta, int num_intensity_levels, bool process_luminance, std::pmr::memory_resource *mr=nullptr)
 Edge-aware fast local Laplacian filtering (B = locallapfilt(I, sigma, alpha, beta, ...)).
Value nk::image::imreducehaze (const Value &I, double amount, const std::string &method, const Value &atmospheric_light, const std::string &contrast_enhancement, double boost_amount, Value &t_out, Value &L_out, std::pmr::memory_resource *mr=nullptr)
 Dark-channel-prior haze removal ([J, T, L] = imreducehaze(I, amount, ...)).
Value nk::image::fibermetric (const Value &I, const std::vector< double > &thickness, double structure_sensitivity, bool bright_polarity, std::pmr::memory_resource *mr=nullptr)
 Multi-scale Frangi vesselness filter (J = fibermetric(I, thickness, ...)).
Value nk::image::fsamp2 (const Value &Hd, const Value &f1, const Value &f2, const std::vector< std::size_t > &siz, std::pmr::memory_resource *mr=nullptr)
 2-D FIR filter design via frequency sampling (h = fsamp2(Hd)).
Value nk::image::ftrans2 (const Value &b, const Value &t, std::pmr::memory_resource *mr=nullptr)
 2-D FIR filter via 1-D → 2-D frequency transformation (h = ftrans2(b, t)).
Value nk::image::fwind1 (const Value &Hd, const Value &win1, const Value &win2, std::pmr::memory_resource *mr=nullptr)
 2-D FIR filter via 1-D window method (h = fwind1(Hd, win1[, win2])).
Value nk::image::fwind2 (const Value &Hd, const Value &W, std::pmr::memory_resource *mr=nullptr)
 2-D FIR filter via 2-D window method (h = fwind2(Hd, W)).
Value nk::image::imresize (const Value &A, double scale, const std::string &method, std::pmr::memory_resource *mr=nullptr)
 Resample an image to a new size by a uniform scale factor (B = imresize(A, scale, method)).
Value nk::image::imresize (const Value &A, size_t outH, size_t outW, const std::string &method, std::pmr::memory_resource *mr=nullptr)
 Resample an image to an explicit output size (B = imresize(A, [outH outW], method)).
Value nk::image::imcrop (const Value &A, double xmin, double ymin, double width, double height, std::pmr::memory_resource *mr=nullptr)
 Crop a rectangular region (B = imcrop(A, [xmin ymin width height])).
Value nk::image::imcrop3 (const Value &V, const Value &cuboid, std::pmr::memory_resource *mr=nullptr)
 Crop a 3-D image volume (VOUT = imcrop3(V, cuboid)).
Value nk::image::imrotate (const Value &A, double angle, const std::string &method, const std::string &bbox, std::pmr::memory_resource *mr=nullptr)
 Rotate an image counter-clockwise (B = imrotate(A, angle, method, bbox)).
Value nk::image::imtranslate (const Value &A, double dx, double dy, std::pmr::memory_resource *mr=nullptr)
 Shift an image by an arbitrary (dx, dy) translation (B = imtranslate(A, [dx dy])).
Value nk::image::axes2pix (double n, const Value &extent, const Value &axesCoord, std::pmr::memory_resource *mr=nullptr)
 World-axis ↔ pixel coordinate mapping (pix = axes2pix(n, extent, axesCoord)).
Value nk::image::imresize3 (const Value &V, size_t outR, size_t outC, size_t outD, const std::string &method, bool antialias, std::pmr::memory_resource *mr=nullptr)
 Resample a 3-D volume to a new size (B = imresize3(V, scale|[r c d], method, ...)).
Value nk::image::imresize3 (const Value &V, double scale, const std::string &method, bool antialias, std::pmr::memory_resource *mr=nullptr)
 Resample a 3-D volume by a uniform scale factor (B = imresize3(V, scale, ...)).
Value nk::image::imrotate3 (const Value &V, double angle_deg, double Wx, double Wy, double Wz, const std::string &method, const std::string &bbox, double fill, std::pmr::memory_resource *mr=nullptr)
 Rotate a 3-D volume around an arbitrary axis (B = imrotate3(V, angle, W, method, bbox, FillValues=v)).
Value nk::image::impyramid (const Value &A, const std::string &type, std::pmr::memory_resource *mr=nullptr)
 Burt–Adelson image pyramid step (B = impyramid(A, type)).
Value nk::image::imread (const std::string &path, std::pmr::memory_resource *mr=nullptr)
 Read an image from disk (A = imread(path)).
void nk::image::imwrite (const Value &A, const std::string &path, std::pmr::memory_resource *mr=nullptr)
 Write an image to disk (imwrite(A, path)).
std::string nk::image::imwriteToBytes (const Value &A, const std::string &ext, std::pmr::memory_resource *mr=nullptr)
 Encode an image to in-memory bytes (companion to imwrite).
Value nk::image::imfinfo (const std::string &path, std::pmr::memory_resource *mr=nullptr)
 Read image header metadata without decoding pixels (S = imfinfo(path)).
Value nk::image::imfinfoFromBytes (const std::string &bytes, const std::string &filename, std::pmr::memory_resource *mr=nullptr)
 imfinfo from already-loaded bytes (the engine entry feeds these from the VFS so it works on the virtual + real filesystem).
Value nk::image::readTiff (const std::string &path, std::pmr::memory_resource *mr=nullptr)
 Minimal TIFF reader for the formats stb doesn't decode.
Value nk::image::readTiff (const std::string &path, std::uint32_t page, std::pmr::memory_resource *mr=nullptr)
 Multi-page form: read the page-th IFD (1-based).
Value nk::image::readTiff (std::vector< std::uint8_t > buf, std::uint32_t page, std::pmr::memory_resource *mr=nullptr)
 Buffer overloads — decode TIFF from already-loaded bytes (the IDE feeds these from the VFS so reads work on the virtual + real filesystem).
std::pair< Value, Value > nk::image::readTiffWithMap (std::vector< std::uint8_t > buf, std::uint32_t page, std::pmr::memory_resource *mr=nullptr)
std::pair< Value, Value > nk::image::readTiffWithMap (const std::string &path, std::uint32_t page, std::pmr::memory_resource *mr=nullptr)
 Two-output read for palette TIFFs: returns (indices, colormap).
void nk::image::peekTiff (const std::string &path, std::uint32_t &W, std::uint32_t &H, std::uint16_t &bits, std::uint16_t &channels)
 Peek a TIFF file's first-IFD metadata without decoding pixels.
void nk::image::peekTiff (const std::vector< std::uint8_t > &buf, std::uint32_t &W, std::uint32_t &H, std::uint16_t &bits, std::uint16_t &channels)
 Buffer overload — peek metadata from already-loaded TIFF bytes (the IDE feeds these from the VFS so imfinfo works on the virtual + real FS).
std::uint32_t nk::image::tiffNumPages (const std::string &path)
 Count the number of IFDs (pages) in a TIFF file.
void nk::image::writeTiff (const Value &A, const std::string &path, const std::string &compression="none", bool appendMode=false)
 Write A to path as a baseline TIFF.
std::vector< std::uint8_t > nk::image::writeTiffToBytes (const Value &A, const std::string &compression="none", const std::vector< std::uint8_t > *existing=nullptr)
 Buffer form — encode A to a TIFF byte vector (the engine entry writes these through the VFS).
Value nk::image::strel (const std::string &shape, const std::vector< double > &params, const Value &arbitrary_nhood, std::pmr::memory_resource *mr=nullptr)
 Build a 2-D structuring element (SE = strel(shape, params, arbitrary_nhood)).
Value nk::image::imerode (const Value &I, const Value &SE, std::pmr::memory_resource *mr=nullptr)
 Grayscale erosion (J = imerode(I, SE)).
Value nk::image::imdilate (const Value &I, const Value &SE, std::pmr::memory_resource *mr=nullptr)
 Grayscale dilation (J = imdilate(I, SE)).
Value nk::image::imopen (const Value &I, const Value &SE, std::pmr::memory_resource *mr=nullptr)
 Morphological opening (J = imopen(I, SE) = imdilate(imerode(I, SE), SE)).
Value nk::image::imclose (const Value &I, const Value &SE, std::pmr::memory_resource *mr=nullptr)
 Morphological closing (J = imclose(I, SE) = imerode(imdilate(I, SE), SE)).
Value nk::image::imreconstruct (const Value &marker, const Value &mask, int conn, std::pmr::memory_resource *mr=nullptr)
 Morphological reconstruction by dilation (J = imreconstruct(marker, mask, conn)).
Value nk::image::imfill_holes (const Value &BW, int conn, std::pmr::memory_resource *mr=nullptr)
 Fill holes in a binary image (J = imfill(BW, 'holes', conn)).
Value nk::image::imregionalmax (const Value &I, int conn, std::pmr::memory_resource *mr=nullptr)
 Regional maxima mask (J = imregionalmax(I, conn)).
Value nk::image::imregionalmin (const Value &I, int conn, std::pmr::memory_resource *mr=nullptr)
 Regional minima mask (J = imregionalmin(I, conn)).
Value nk::image::imhmax (const Value &I, double h, int conn, std::pmr::memory_resource *mr=nullptr)
 H-maxima transform (J = imhmax(I, h, conn)).
Value nk::image::imhmin (const Value &I, double h, int conn, std::pmr::memory_resource *mr=nullptr)
 H-minima transform (J = imhmin(I, h, conn)) — dual of imhmax.
Value nk::image::imextendedmax (const Value &I, double h, int conn, std::pmr::memory_resource *mr=nullptr)
 Extended-maxima transform (J = imextendedmax(I, h, conn)).
Value nk::image::imextendedmin (const Value &I, double h, int conn, std::pmr::memory_resource *mr=nullptr)
 Extended-minima transform (J = imextendedmin(I, h, conn)).
Value nk::image::imimposemin (const Value &I, const Value &BW, int conn, std::pmr::memory_resource *mr=nullptr)
 Minima imposition (J = imimposemin(I, BW, conn)).
Value nk::image::imclearborder (const Value &BW, int conn, std::pmr::memory_resource *mr=nullptr)
 Remove border-touching components (J = imclearborder(BW, conn)).
Value nk::image::imkeepborder (const Value &BW, int conn, std::pmr::memory_resource *mr=nullptr)
 Keep only border-touching components (J = imkeepborder(BW, conn)) — dual of imclearborder.
Value nk::image::imtophat (const Value &I, const Value &SE, std::pmr::memory_resource *mr=nullptr)
 White top-hat (J = imtophat(I, SE) = I - imopen(I, SE)).
Value nk::image::imbothat (const Value &I, const Value &SE, std::pmr::memory_resource *mr=nullptr)
 Black top-hat (J = imbothat(I, SE) = imclose(I, SE) - I).
Value nk::image::mmgradm (const Value &I, const Value &se_dil, const Value &se_ero, std::pmr::memory_resource *mr=nullptr)
 Morphological gradient (G = mmgradm(I, se_dil, se_ero)).
Value nk::image::bwpack (const Value &BW, std::pmr::memory_resource *mr=nullptr)
 Pack a binary image into UINT32 columns (BWP = bwpack(BW)).
Value nk::image::bwunpack (const Value &BWP, size_t M, std::pmr::memory_resource *mr=nullptr)
 Unpack a UINT32 binary image (BW = bwunpack(BWP, M)).
Value nk::image::applylut (const Value &BW, const Value &LUT, std::pmr::memory_resource *mr=nullptr)
 Neighbourhood-LUT filter (A = applylut(BW, LUT)).
Value nk::image::bwlookup (const Value &BW, const Value &lut, std::pmr::memory_resource *mr=nullptr)
 Nonlinear neighbourhood filter via lookup table (A = bwlookup(BW, lut)).
Value nk::image::makelut (FnHandle fun, int n, std::pmr::memory_resource *mr=nullptr)
 Build a lookup table for bwlookup (lut = makelut(fun, n)).
Value nk::image::bwmorph3 (const Value &V, const std::string &op, std::pmr::memory_resource *mr=nullptr)
 Morphological operations on a binary volume (J = bwmorph3(V, operation)).
Value nk::image::bwhitmiss (const Value &BW, const Value &se1, const Value &se2, std::pmr::memory_resource *mr=nullptr)
 Binary hit-or-miss transform (J = bwhitmiss(BW, se1, se2)).
Value nk::image::bwmorph (const Value &BW, const std::string &op, int n, std::pmr::memory_resource *mr=nullptr)
 Composite binary morphological operations (J = bwmorph(BW, op, n)).
Value nk::image::bwtraceboundary (const Value &BW, const Value &P, const std::string &fstep, int conn, std::size_t m, const std::string &dir, std::pmr::memory_resource *mr=nullptr)
 Trace object boundary in a binary image (B = bwtraceboundary(BW, P, fstep, conn, m, dir)).
std::tuple< Value, Value > nk::image::imgradientxy (const Value &I, const std::string &method, std::pmr::memory_resource *mr=nullptr)
 Component gradients ([Gx, Gy] = imgradientxy(I, method)).
std::tuple< Value, Value > nk::image::imgradient (const Value &I, const std::string &method, std::pmr::memory_resource *mr=nullptr)
 Gradient magnitude and direction ([Gmag, Gdir] = imgradient(I, method)).
std::tuple< Value, Value, Value > nk::image::imgradientxyz (const Value &V, const std::string &method, std::pmr::memory_resource *mr=nullptr)
 3-D component gradients ([Gx, Gy, Gz] = imgradientxyz(V, method)).
std::tuple< Value, Value, Value > nk::image::imgradient3 (const Value &V, const std::string &method, std::pmr::memory_resource *mr=nullptr)
 3-D gradient magnitude + spherical direction ([Gmag, Gaz, Gelev] = imgradient3(V, method) or (Gx, Gy, Gz) inputs).
std::tuple< Value, Value, Value > nk::image::imgradient3_from_grads (const Value &Gx, const Value &Gy, const Value &Gz, std::pmr::memory_resource *mr=nullptr)
Value nk::image::edge (const Value &I, const std::string &method, double thresh_lo, double thresh_hi, std::pmr::memory_resource *mr=nullptr)
 Binary edge map (BW = edge(I, method, thresh_lo, thresh_hi)).
Value nk::image::cornermetric (const Value &I, const std::string &method, double sensitivity_factor, const Value &filter_coef, std::pmr::memory_resource *mr=nullptr)
 Corner metric matrix (C = cornermetric(I, method, ...)).
Value nk::image::corner (const Value &I, const std::string &method, int maxN, double quality_level, double sensitivity, const Value &filter_coef, std::pmr::memory_resource *mr=nullptr)
 Detect corner points (C = corner(I, ...)).
void nk::image::hough (const Value &BW, double rho_res, const Value &theta_deg, Value &H_out, Value &T_out, Value &R_out, std::pmr::memory_resource *mr=nullptr)
 Standard Hough transform ([H, T, R] = hough(BW, ...)).
Value nk::image::houghpeaks (const Value &H, std::size_t numpeaks, double threshold, std::size_t nhoodRho, std::size_t nhoodTheta, const Value &theta_deg, std::pmr::memory_resource *mr=nullptr)
 Find peaks in a Hough-transform accumulator (P = houghpeaks(H, NumPeaks, ...)).
Value nk::image::houghlines (const Value &BW, const Value &theta_deg, const Value &rho, const Value &peaks, double fillgap, double minlength, std::pmr::memory_resource *mr=nullptr)
 Extract line segments from Hough-transform peaks (lines = houghlines(BW, theta, rho, peaks, ...)).
Value nk::image::immse (const Value &A, const Value &B, std::pmr::memory_resource *mr=nullptr)
 Mean squared error (err = immse(A, B)).
Value nk::image::psnr (const Value &A, const Value &B, double peak, std::pmr::memory_resource *mr=nullptr)
 Peak signal-to-noise ratio (r = psnr(A, B, peak)).
Value nk::image::ssim (const Value &A, const Value &B, std::pmr::memory_resource *mr=nullptr)
 Structural similarity index (r = ssim(A, B)).
Value nk::image::corr2 (const Value &A, const Value &B, std::pmr::memory_resource *mr=nullptr)
 2-D correlation coefficient (r = corr2(A, B)).
Value nk::image::mean2 (const Value &A, std::pmr::memory_resource *mr=nullptr)
 Mean of every element (m = mean2(A)).
Value nk::image::std2 (const Value &A, std::pmr::memory_resource *mr=nullptr)
 Standard deviation of every element (s = std2(A)).
Value nk::image::multissim (const Value &A, const Value &Iref, int num_scales, const std::vector< double > &scale_weights, double sigma, double dynamic_range, std::vector< Value > *quality_maps_out, std::pmr::memory_resource *mr=nullptr)
 Multi-scale structural similarity index ([score, qmaps] = multissim(I, Iref, ...)).
Value nk::image::multissim3 (const Value &V, const Value &Vref, int num_scales, const std::vector< double > &scale_weights, double sigma, double dynamic_range, std::vector< Value > *quality_maps_out, std::pmr::memory_resource *mr=nullptr)
 3-D multi-scale SSIM ([score, qmaps] = multissim3(V, Vref, ...)).
std::tuple< Value, Value > nk::image::bwlabel (const Value &BW, int conn, std::pmr::memory_resource *mr=nullptr)
 Connected-component labelling ([L, num] = bwlabel(BW, conn)).
Value nk::image::bwconncomp (const Value &BW, int conn, std::pmr::memory_resource *mr=nullptr)
 Connected-component struct (CC = bwconncomp(BW, conn)).
Value nk::image::labelmatrix (const Value &CC, std::pmr::memory_resource *mr=nullptr)
 Connected-component label matrix (L = labelmatrix(CC)).
Value nk::image::cc2bw (const Value &CC, const Value &objects_to_keep, std::pmr::memory_resource *mr=nullptr)
 Reconstruct binary image from a bwconncomp struct (BW = cc2bw(CC, ...)).
Value nk::image::bwpropfilt (const Value &BW, const Value &CC, const Value &marker, const std::string &attribute, double p_min, double p_max, std::size_t keep_n, bool keep_largest, int conn, std::pmr::memory_resource *mr=nullptr)
 Filter connected components by attribute value (BW2 = bwpropfilt(BW, attrib, range_or_n, ...)).
Value nk::image::bwarea (const Value &BW, std::pmr::memory_resource *mr=nullptr)
 Total foreground area (A = bwarea(BW)).
Value nk::image::bwperim (const Value &BW, int conn, std::pmr::memory_resource *mr=nullptr)
 Perimeter mask (BW2 = bwperim(BW, conn)).
Value nk::image::bwareaopen (const Value &BW, int P, int conn, std::pmr::memory_resource *mr=nullptr)
 Remove small components (BW2 = bwareaopen(BW, P, conn)).
Value nk::image::bwboundaries (const Value &BW, int conn, Value *Lout=nullptr, int *Nout=nullptr, std::pmr::memory_resource *mr=nullptr)
 Trace boundary contours (B = bwboundaries(BW, conn)).
Value nk::image::regionprops (const Value &BW_or_L, const std::vector< std::string > &props, const Value &intensity, std::pmr::memory_resource *mr=nullptr)
 Per-region descriptors (S = regionprops(BW_or_L, props)).
Value nk::image::bwdist (const Value &BW, std::pmr::memory_resource *mr=nullptr)
 Euclidean distance transform (D = bwdist(BW)).
Value nk::image::roicolor (const Value &A, const Value &low_or_v, double high, bool is_range, std::pmr::memory_resource *mr=nullptr)
 Region-of-interest mask (BW = roicolor(A, low, high)).
Value nk::image::fchcode (const Value &bound, std::pmr::memory_resource *mr=nullptr)
 Freeman 8-direction chain code (fcc = fchcode(bound)).
Value nk::image::bweuler (const Value &BW, int conn, std::pmr::memory_resource *mr=nullptr)
 Euler number objects − holes (E = bweuler(BW, conn)).
Value nk::image::bwareafilt (const Value &BW, double lo, double hi, size_t n_keep, bool keep_largest, int conn, std::pmr::memory_resource *mr=nullptr)
 Filter connected components by area (BW2 = bwareafilt(...)).
std::tuple< Value, Value > nk::image::bwselect (const Value &BW, const Value &cols, const Value &rows, int conn, std::pmr::memory_resource *mr=nullptr)
 Select components by seed pixels ([BW2, idx] = bwselect(BW, cols, rows, conn)).
Value nk::image::dice (const Value &A, const Value &B, std::pmr::memory_resource *mr=nullptr)
 Sørensen–Dice similarity coefficient (d = dice(BW1, BW2)).
Value nk::image::jaccard (const Value &A, const Value &B, std::pmr::memory_resource *mr=nullptr)
 Intersection-over-union (j = jaccard(BW1, BW2)).
Value nk::image::boundarymask (const Value &L_or_BW, int conn, std::pmr::memory_resource *mr=nullptr)
 Boundary mask of a labeled or binary image (BW = boundarymask(L, conn)).
Value nk::image::label2idx (const Value &L, std::pmr::memory_resource *mr=nullptr)
 Group label-image pixels into per-label index lists (idx = label2idx(L)).
Value nk::image::grayconnected (const Value &I, int row, int col, double tol, std::pmr::memory_resource *mr=nullptr)
 Flood-fill region from a seed pixel (BW = grayconnected(I, row, col, tol)).
Value nk::image::graydiffweight (const Value &I, double ref_gray_val, double rolloff_factor, double cutoff, std::pmr::memory_resource *mr=nullptr)
 Pixel weights from grayscale intensity difference (W = graydiffweight(I, refGrayVal [, NV...])).
Value nk::image::gradientweight (const Value &I, double sigma_x, double sigma_y, double rolloff_factor, double weight_cutoff, std::pmr::memory_resource *mr=nullptr)
 Pixel weights from image gradient magnitude (W = gradientweight(I [, sigma], 'RolloffFactor', P, 'WeightCutoff', K)).
Value nk::image::regionfill (const Value &I, const Value &mask, std::pmr::memory_resource *mr=nullptr)
 Fill image regions via inward Laplacian interpolation (J = regionfill(I, MASK)).
Value nk::image::poly2mask (const Value &X, const Value &Y, std::size_t M, std::size_t N, std::pmr::memory_resource *mr=nullptr)
 Convert polygon to binary mask (BW = poly2mask(X, Y, M, N)).
Value nk::image::reducepoly (const Value &P, double tolerance, std::pmr::memory_resource *mr=nullptr)
 Reduce point density of a polyline / polygon (P_reduced = reducepoly(P, tolerance)).
Value nk::image::roipoly (double xdata_lo, double xdata_hi, double ydata_lo, double ydata_hi, std::size_t M, std::size_t N, const Value &xi, const Value &yi, std::pmr::memory_resource *mr=nullptr)
 Polygonal region-of-interest mask (BW = roipoly(A, xi, yi), world-coord variants).
Value nk::image::graydist (const Value &I, const Value &seeds, const std::string &method, std::pmr::memory_resource *mr=nullptr)
 Gray-weighted geodesic distance transform (T = graydist(I, seeds [, method])).
Value nk::image::bwdistgeodesic (const Value &BW, const Value &seeds, const std::string &method, std::pmr::memory_resource *mr=nullptr)
 Geodesic distance transform of binary image (D = bwdistgeodesic(BW, seeds [, method])).
Value nk::image::imoverlay (const Value &I, const Value &BW, const Value &color, std::pmr::memory_resource *mr=nullptr)
 Paint a binary mask onto an image with a colour (J = imoverlay(I, BW, color)).
Value nk::image::graycomatrix (const Value &I, int numLevels, int offR, int offC, double gLow, double gHigh, bool symmetric, std::pmr::memory_resource *mr=nullptr)
 Gray-level co-occurrence matrix (G = graycomatrix(I, ...)).
Value nk::image::graycoprops (const Value &G, std::pmr::memory_resource *mr=nullptr)
 Texture statistics from a GLCM (S = graycoprops(G)).
Value nk::image::dct2 (const Value &A, std::pmr::memory_resource *mr=nullptr)
 2-D Type-II orthonormal DCT (B = dct2(A)).
Value nk::image::idct2 (const Value &B, std::pmr::memory_resource *mr=nullptr)
 Inverse 2-D DCT (A = idct2(B)).
Value nk::image::dctmtx (double N, std::pmr::memory_resource *mr=nullptr)
 N × N DCT-II transform matrix (D = dctmtx(N)).
Value nk::image::integralImage (const Value &I, std::pmr::memory_resource *mr=nullptr)
 Summed-area table (J = integralImage(I)).
Value nk::image::integralImage3 (const Value &V, std::pmr::memory_resource *mr=nullptr)
 3-D summed-volume table (J = integralImage3(V)).
Value nk::image::checkerboard (size_t side, size_t M, size_t N, std::pmr::memory_resource *mr=nullptr)
 Checkerboard test pattern (I = checkerboard(side, M, N)).
Value nk::image::normxcorr2 (const Value &templ, const Value &img, std::pmr::memory_resource *mr=nullptr)
 Normalised cross-correlation (C = normxcorr2(template, img)).
Value nk::image::psf2otf (const Value &PSF, Span< const size_t > outsize={}, std::pmr::memory_resource *mr=nullptr)
 PSF → OTF (OTF = psf2otf(PSF, outsize)).
Value nk::image::fftconv2 (const Value &A, const Value &B, const std::string &shape, std::pmr::memory_resource *mr=nullptr)
 2-D convolution via FFT (Y = fftconv2(A, B, shape)).
Value nk::image::deconvwnr (const Value &I, const Value &PSF, double nsr, std::pmr::memory_resource *mr=nullptr)
 Wiener deconvolution (J = deconvwnr(I, PSF, NSR) / deconvwnr(I, PSF, NCORR, ICORR)).
Value nk::image::deconvwnr (const Value &I, const Value &PSF, const Value &ncorr, const Value &icorr, std::pmr::memory_resource *mr=nullptr)
 Wiener deconvolution using autocorrelation functions (J = deconvwnr(I, PSF, NCORR, ICORR)).
DeconvregResult nk::image::deconvreg (const Value &I, const Value &PSF, double np, double lo, double hi, const Value &regop, std::pmr::memory_resource *mr=nullptr)
 Tikhonov-regularized deconvolution ([J, LAGRA] = deconvreg(I, PSF, NP, ...)).
Value nk::image::edgetaper (const Value &I, const Value &PSF, std::pmr::memory_resource *mr=nullptr)
 Taper image edges via blur (J = edgetaper(I, PSF)).
Value nk::image::bestblk (const Value &IMS, double k, std::pmr::memory_resource *mr=nullptr)
 Best block size for block-wise processing (siz = bestblk(IMS, k)).
Value nk::image::otf2psf (const Value &OTF, Span< const size_t > outsize={}, std::pmr::memory_resource *mr=nullptr)
 OTF → PSF (PSF = otf2psf(OTF, outsize)).
std::tuple< Value, Value > nk::image::phantom (const Value &model_or_E, size_t n, std::pmr::memory_resource *mr=nullptr)
 Shepp-Logan computational head phantom ([P, E] = phantom(model_or_E, n)).
Value nk::image::im2double (const Value &x, std::pmr::memory_resource *mr=nullptr)
 Convert to DOUBLE in [0, 1] (B = im2double(A)).
Value nk::image::im2single (const Value &x, std::pmr::memory_resource *mr=nullptr)
 Convert to SINGLE in [0, 1] (B = im2single(A)).
Value nk::image::im2uint8 (const Value &x, std::pmr::memory_resource *mr=nullptr)
 Convert to UINT8 (B = im2uint8(A)).
Value nk::image::im2uint16 (const Value &x, std::pmr::memory_resource *mr=nullptr)
 Convert to UINT16 (B = im2uint16(A)).
Value nk::image::im2int16 (const Value &x, std::pmr::memory_resource *mr=nullptr)
 Convert to INT16 (B = im2int16(A)).
Value nk::image::mat2gray (const Value &x, double lo=std::numeric_limits< double >::quiet_NaN(), double hi=std::numeric_limits< double >::quiet_NaN(), std::pmr::memory_resource *mr=nullptr)
 Linear rescale to [0, 1] DOUBLE (B = mat2gray(A, lo, hi)).
Value nk::image::im2gray (const Value &x, std::pmr::memory_resource *mr=nullptr)
 RGB → grayscale dispatcher (Y = im2gray(X)).
Value nk::image::rgb2gray (const Value &x, std::pmr::memory_resource *mr=nullptr)
 Rec.
Value nk::image::getrangefromclass (const Value &I, std::pmr::memory_resource *mr=nullptr)
 Class display range (r = getrangefromclass(I)).
std::tuple< Value, Value > nk::image::gray2ind (const Value &I, int n, std::pmr::memory_resource *mr=nullptr)
 Grayscale → indexed ([ind, map] = gray2ind(I, n)).
Value nk::image::ind2gray (const Value &idx, const Value &map, std::pmr::memory_resource *mr=nullptr)
 Indexed → grayscale (I = ind2gray(idx, map)).
Value nk::image::ind2rgb (const Value &idx, const Value &map, std::pmr::memory_resource *mr=nullptr)
 Indexed → RGB (RGB = ind2rgb(idx, map)).
Value nk::image::iptnum2ordinal (double n, std::pmr::memory_resource *mr=nullptr)
 English ordinal-form string (s = iptnum2ordinal(n)).
Value nk::image::imcast (const Value &I, const std::string &type, std::pmr::memory_resource *mr=nullptr)
 Generic class converter (B = imcast(I, type)).
Value nk::image::isbw (const Value &BW, const std::string &mode, std::pmr::memory_resource *mr=nullptr)
 Binary-image predicate (tf = isbw(BW, mode)).
Value nk::image::isgray (const Value &I, std::pmr::memory_resource *mr=nullptr)
 Grayscale-image predicate (tf = isgray(I)).
Value nk::image::isind (const Value &I, std::pmr::memory_resource *mr=nullptr)
 Indexed-image predicate (tf = isind(I)).
Value nk::image::isrgb (const Value &I, std::pmr::memory_resource *mr=nullptr)
 RGB-image predicate (tf = isrgb(I)).
Value nk::image::iscolormap (const Value &cmap, std::pmr::memory_resource *mr=nullptr)
 Colormap-shape predicate (tf = iscolormap(cmap)).
Value nk::image::intlut (const Value &A, const Value &LUT, std::pmr::memory_resource *mr=nullptr)
 Apply a look-up table to an integer image (B = intlut(A, LUT)).

Detailed Description

Color space conversions, morphological operations, 2D spatial filtering, geometric transformations, and quality metrics (SSIM, PSNR).

Enumeration Type Documentation

◆ PadMode

enum class nk::image::PadMode
strong

Boundary handling for image filtering / padding.

Enumerator
Constant 

pad with pad_value

Replicate 

repeat edge pixel

Symmetric 

mirror without duplicating edge: a b c | b a

Circular 

wrap-around

Definition at line 28 of file image/include/nk/image/filter/filter.hpp.

Function Documentation

◆ adapthisteq()

Value nk::image::adapthisteq ( const Value & I,
const AdaptHistEqOptions & opts = {},
std::pmr::memory_resource * mr = nullptr )

Contrast Limited Adaptive Histogram Equalisation (J = adapthisteq(I, opts)).

Divides the image into numTilesR × numTilesC regions, builds a clipped-redistribute histogram per tile, and applies the bilinearly-interpolated per-tile CDF as the per-pixel transfer function. Full argument set: NumTiles, ClipLimit, NBins, Range, Distribution, Alpha.

Clean-room implementation from public references (CLAHE — Zuiderveld 1994; contrast limiting — Pizer et al. 1990; non-uniform target distributions — Pizer et al. 1987). See.

Parameters
I2-D greyscale image. Returned in the same class.
optsAlgorithm parameters; see AdaptHistEqOptions.
mrMemory resource (nullptr → process default).
Note
2-D greyscale input only; RGB / N-D input throws m:adapthisteq:unsupportedShape.
Value J1 = adapthisteq(I); // defaults
opts.clipLimit = 0.03;
opts.numTilesR = 16;
opts.numTilesC = 16;
Value J2 = adapthisteq(I, opts);
Core MATLAB-compatible multidimensional array and scalar value type.
Definition value.hpp:61
Value adapthisteq(const Value &I, const AdaptHistEqOptions &opts={}, std::pmr::memory_resource *mr=nullptr)
Contrast Limited Adaptive Histogram Equalisation (J = adapthisteq(I, opts)).
Parameters for adapthisteq.
Definition contrast.hpp:107
double clipLimit
Histogram clip fraction in [0, 1]; 0 disables clipping.
Definition contrast.hpp:117
int numTilesC
NumTiles along the column axis.
Definition contrast.hpp:113
int numTilesR
NumTiles along the row axis.
Definition contrast.hpp:110
See also
histeq, imadjust

◆ adaptthresh()

Value nk::image::adaptthresh ( const Value & I,
double sensitivity,
int neighborhood,
const std::string & statistic,
std::pmr::memory_resource * mr = nullptr )

Locally adaptive threshold matrix (T = adaptthresh(I, ...)).

Computes a per-pixel threshold matrix in [0, 1]. Pair with imbinarize(I, T) for adaptive thresholding.

Parameters
IInput image.
sensitivityIn [0, 1], default 0.5. Higher → more pixels classified as foreground (lower local threshold).
neighborhoodFilter size in pixels (odd). Default 2·floor(min(H,W)/16) + 1.
statistic"mean" (default, box filter) or "gaussian" (σ ≈ neighborhood/6).
mrMemory resource (nullptr → process default).
Returns
Threshold matrix in [0, 1].
See also
imbinarize, graythresh

◆ applylut()

Value nk::image::applylut ( const Value & BW,
const Value & LUT,
std::pmr::memory_resource * mr = nullptr )

Neighbourhood-LUT filter (A = applylut(BW, LUT)).

LUT length must be 2^(n²) for some n; common choices are n = 2 (length 16) and n = 3 (length 512). Each output pixel is the LUT entry indexed by the bit pattern of its n × n neighbourhood (zero-padded), with kernel weights reshape(2^[nq-1:-1:0], n, n).

Parameters
BWBinary input.
LUTLookup table (length 2^(n²)).
mrMemory resource (nullptr → process default).
Returns
Filtered image, same shape as BW.
See also
bwmorph

◆ autumn_cmap()

Value nk::image::autumn_cmap ( int n,
std::pmr::memory_resource * mr = nullptr )

Red → yellow colormap (map = autumn(n)).

r = 1, g = (0:n-1)/(n-1), b = 0.

Parameters
nRow count.
mrMemory resource.
Returns
n × 3 colormap.

◆ axes2pix()

Value nk::image::axes2pix ( double n,
const Value & extent,
const Value & axesCoord,
std::pmr::memory_resource * mr = nullptr )

World-axis ↔ pixel coordinate mapping (pix = axes2pix(n, extent, axesCoord)).

Maps user-axis coordinates back to 1-based intrinsic pixel coordinates assuming the first / last pixel centres lie at extent(1) / extent(end). Degenerate cases (n = 1 or extent(1) == extent(end)) collapse the mapping to a translation.

Parameters
nPixel count along the axis.
extentTwo-element vector [low, high] of axis bounds.
axesCoordArray of axis-space coordinates to convert.
mrMemory resource (nullptr → process default).
Returns
Pixel-space coordinates, same shape as axesCoord.

◆ bestblk()

Value nk::image::bestblk ( const Value & IMS,
double k,
std::pmr::memory_resource * mr = nullptr )

Best block size for block-wise processing (siz = bestblk(IMS, k)).

For each dim of IMS: keep it if it's <= k (default 100); else scan from k down to max(dim/10, k/2) and pick the largest size with the smallest mod-padding mod(-dim, p).

Parameters
IMSImage size vector.
kMaximum block size (default 100).
mrMemory resource (nullptr → process default).
Returns
Best block size vector.

◆ bone_cmap()

Value nk::image::bone_cmap ( int n,
std::pmr::memory_resource * mr = nullptr )

Grayscale-with-blue-tint colormap (map = bone(n)).

Per-channel piecewise ramps with idx_R = floor(3/4 · n), idx_G = floor(3/8 · n).

Parameters
nRow count.
mrMemory resource.
Returns
n × 3 colormap.

◆ boundarymask()

Value nk::image::boundarymask ( const Value & L_or_BW,
int conn,
std::pmr::memory_resource * mr = nullptr )

Boundary mask of a labeled or binary image (BW = boundarymask(L, conn)).

For a label image: marks every pixel that has at least one connectivity-neighbour with a different label (i.e. a region edge). For a binary mask: returns the foreground perimeter, similar to the bwperim operation.

Parameters
L_or_BWLabel image (any integer class) or binary mask.
connConnectivity — 4 or 8 (default 8).
mrMemory resource (nullptr → process default).
Returns
Logical boundary mask of the same H × W.

◆ brighten()

Value nk::image::brighten ( const Value & map,
double beta,
std::pmr::memory_resource * mr = nullptr )

Gamma-adjust a colormap (rmap = brighten(map, beta)).

gamma = 1 - β for β > 0 (brighter), gamma = 1/(1 + β) for β <= 0 (darker). β outside (-1, 1) throws.

Parameters
mapInput N × 3 colormap.
betaGamma adjustment in (-1, 1).
mrMemory resource (nullptr → process default).
Returns
Adjusted colormap.
Exceptions
Errorbeta out of range.

◆ bwarea()

Value nk::image::bwarea ( const Value & BW,
std::pmr::memory_resource * mr = nullptr )

Total foreground area (A = bwarea(BW)).

Returns the integer pixel count (the optional quarter-pixel boundary correction is not applied).

Parameters
BWBinary image.
mrMemory resource (nullptr → process default).
Returns
Scalar area in pixels.
See also
bwperim

◆ bwareafilt()

Value nk::image::bwareafilt ( const Value & BW,
double lo,
double hi,
size_t n_keep,
bool keep_largest,
int conn,
std::pmr::memory_resource * mr = nullptr )

Filter connected components by area (BW2 = bwareafilt(...)).

Two selection modes:

  • Range mode (lo and hi finite): keep components whose area lies in [lo, hi].
  • Top-N mode (n_keep > 0): keep the n_keep largest (keep_largest = true) or smallest (false) components.
Parameters
BWBinary input.
loRange lower bound (range mode).
hiRange upper bound (range mode).
n_keepComponent count (top-N mode).
keep_largestTie-break direction for top-N.
connConnectivity (4 or 8; default 8).
mrMemory resource (nullptr → process default).
Returns
Logical mask, same H×W as BW.

◆ bwareaopen()

Value nk::image::bwareaopen ( const Value & BW,
int P,
int conn,
std::pmr::memory_resource * mr = nullptr )

Remove small components (BW2 = bwareaopen(BW, P, conn)).

Drops every connected component with fewer than P foreground pixels.

Parameters
BWBinary image.
PMinimum component size (pixels).
connConnectivity (4 or 8).
mrMemory resource (nullptr → process default).
Returns
Filtered LOGICAL mask, same shape as BW.
See also
bwareafilt

◆ bwboundaries()

Value nk::image::bwboundaries ( const Value & BW,
int conn,
Value * Lout = nullptr,
int * Nout = nullptr,
std::pmr::memory_resource * mr = nullptr )

Trace boundary contours (B = bwboundaries(BW, conn)).

Moore-neighbour walking with Jacob's stopping criterion. Returns a cell column where each entry is a P×2 uint32 matrix listing [row col] boundary pixels in clockwise order, with the start pixel appended as the closing entry.

Parameters
BWBinary image.
connConnectivity (4 or 8).
LoutOptional: receives the H×W label matrix (objects 1..N; holes are NOT labelled — this is the 'noholes' behaviour).
NoutOptional: receives the number of objects.
mrMemory resource (nullptr → process default).
Returns
Cell column of P×2 coordinate arrays.
See also
bwperim, bwconncomp

◆ bwconncomp()

Value nk::image::bwconncomp ( const Value & BW,
int conn,
std::pmr::memory_resource * mr = nullptr )

Connected-component struct (CC = bwconncomp(BW, conn)).

Returns a 1×1 struct with fields:

  • Connectivity — scalar (conn).
  • ImageSize — [H W].
  • NumObjects — scalar count.
  • PixelIdxList — 1×K cell of column-vectors of 1-based linear (column-major) indices per component.
Parameters
BWBinary image.
connConnectivity — 4 or 8 (default 8).
mrMemory resource (nullptr → process default).
Returns
Struct Value with the fields described above.
See also
bwlabel

◆ bwdist()

Value nk::image::bwdist ( const Value & BW,
std::pmr::memory_resource * mr = nullptr )

Euclidean distance transform (D = bwdist(BW)).

For each pixel, the distance to the nearest non-zero pixel in BW. Foreground pixels themselves get distance 0; an all-zero input yields +Inf everywhere. Implementation is the Felzenszwalb–Huttenlocher 1-D parabolic-envelope DT applied row-wise then column-wise — exact, O(H·W).

Parameters
BWBinary image.
mrMemory resource (nullptr → process default).
Returns
DOUBLE distance map, same shape as BW.

◆ bwdistgeodesic()

Value nk::image::bwdistgeodesic ( const Value & BW,
const Value & seeds,
const std::string & method,
std::pmr::memory_resource * mr = nullptr )

Geodesic distance transform of binary image (D = bwdistgeodesic(BW, seeds [, method])).

Like graydist, but the underlying image is a logical mask BW — only true pixels are traversable, and the edge cost reduces to the raw chamfer distance χ(p, q) (no intensity weighting). Returned distances are:

  • 0 at seed pixels,
  • positive finite values for traversable, reachable pixels,
  • NaN for pixels where BW is false,
  • Inf for traversable but unreachable pixels.

Output class is always SINGLE.

Reference: P. Soille, Morphological Image Analysis, 2nd ed., Springer, §4.4 (chamfer geodesic distance).

Parameters
BW2-D binary mask (logical or numeric non-zero).
seedsLinear seed indices (1-based, into column-major storage of BW). Must point to true pixels.
method"chessboard" (default) / "cityblock" / "quasi-euclidean".
mrMemory resource (nullptr → process default).
Returns
SINGLE distance transform, same shape as BW.

◆ bweuler()

Value nk::image::bweuler ( const Value & BW,
int conn,
std::pmr::memory_resource * mr = nullptr )

Euler number objects − holes (E = bweuler(BW, conn)).

Computed via Pratt's bit-quad LUT method.

Parameters
BWBinary image.
connForeground connectivity — 4 or 8 (default 8).
mrMemory resource (nullptr → process default).
Returns
Scalar Euler number.

◆ bwhitmiss()

Value nk::image::bwhitmiss ( const Value & BW,
const Value & se1,
const Value & se2,
std::pmr::memory_resource * mr = nullptr )

Binary hit-or-miss transform (J = bwhitmiss(BW, se1, se2)).

\( J = \text{imerode}(BW, se_1)\ \wedge\ \text{imerode}(\sim BW, se_2) \). se1 marks foreground requirements; se2 marks background requirements. They must have disjoint neighbourhoods to be meaningful (not enforced).

Parameters
BWBinary input.
se1Foreground SE.
se2Background SE.
mrMemory resource (nullptr → process default).
Returns
Binary hit-or-miss output.

◆ bwlabel()

std::tuple< Value, Value > nk::image::bwlabel ( const Value & BW,
int conn,
std::pmr::memory_resource * mr = nullptr )

Connected-component labelling ([L, num] = bwlabel(BW, conn)).

Two-pass union-find labelling. Returns the label image as uint16 (0 = background) and the component count.

Parameters
BWBinary image.
connConnectivity — 4 or 8 (default 8).
mrMemory resource (nullptr → process default).
Returns
(L, num); bind via auto [L, num] = bwlabel(BW, 8);.
See also
bwconncomp, bwareaopen, bwselect

◆ bwlookup()

Value nk::image::bwlookup ( const Value & BW,
const Value & lut,
std::pmr::memory_resource * mr = nullptr )

Nonlinear neighbourhood filter via lookup table (A = bwlookup(BW, lut)).

Performs a 2×2 (lut length 16) or 3×3 (lut length 512) nonlinear neighbourhood filtering operation on binary image BW. Each output pixel is lut indexed by the bit pattern of its neighbourhood (zero-padded at the border), with the same index convention as applylut / makelut. The modern replacement for applylut, restricted to the documented 16- and 512-element table sizes.

Parameters
BWBinary input (logical or numeric, treated as BW != 0).
lutLookup table — exactly 16 or 512 elements.
mrMemory resource (nullptr → process default).
Returns
Filtered image, same shape as BW, class of lut.
Exceptions
Errorlut not 16 or 512 elements.
See also
makelut, applylut

◆ bwmorph()

Value nk::image::bwmorph ( const Value & BW,
const std::string & op,
int n,
std::pmr::memory_resource * mr = nullptr )

Composite binary morphological operations (J = bwmorph(BW, op, n)).

Each named operation corresponds to a 512-entry LUT (or a chain of LUTs and bitwise compositions), indexed by the 3×3 neighbourhood of every pixel. Out-of-bounds pixels are 0.

Supported operations (case-sensitive — caller normalises):

  • single-LUT: "bridge", "clean", "diag", "dilate", "endpoints", "erode", "fatten", "fill", "hbreak", "majority", "perim4", "perim8", "remove".
  • composite chains: "bothat", "close", "open", "tophat", "shrink", "skeleton", "spur", "thin", "thicken", "branchpoints".
Parameters
BWBinary input.
opOperation name.
nIteration count. n = -1 means "until stable" (i.e. Inf iterations); n = 1 is the default.
mrMemory resource (nullptr → process default).
Returns
Processed binary image.
Exceptions
ErrorUnknown op (m:bwmorph:badOp).

◆ bwmorph3()

Value nk::image::bwmorph3 ( const Value & V,
const std::string & op,
std::pmr::memory_resource * mr = nullptr )

Morphological operations on a binary volume (J = bwmorph3(V, operation)).

Evaluates each voxel from its 3×3×3 neighbourhood (zero-padded at the border). With count = number of set voxels in the 27-neighbourhood including the centre and faces6 = the six 6-connected face neighbours:

operation rule
branchpoints centre set and count > 3
clean centre set and count != 1
endpoints centre set and count == 2
fill centre set or faces6 == 6
majority count > 13 (≥ 14 of 27)
remove centre set and faces6 != 6

Accepts a 2-D image (treated as a single-plane volume) or a 3-D volume; the output is always LOGICAL of the same size. Input is taken as V != 0. Clean-room port of MATLAB R2025b's bwmorph3 rules.

Parameters
VBinary volume (numeric or logical, 2-D or 3-D).
opOne of branchpoints / clean / endpoints / fill / majority / remove.
mrMemory resource (nullptr → process default).
Returns
LOGICAL volume, same size as V.
Exceptions
ErrorUnknown operation, or rank > 3.
See also
bwmorph, bwskel, imerode, imdilate

◆ bwpack()

Value nk::image::bwpack ( const Value & BW,
std::pmr::memory_resource * mr = nullptr )

Pack a binary image into UINT32 columns (BWP = bwpack(BW)).

Each 32 rows of BW become one UINT32; bit 0 corresponds to the first row, bit 31 to the 32nd. Output rows = ceil(M / 32). Zero-padded if M is not a multiple of 32.

Parameters
BWLOGICAL image.
mrMemory resource (nullptr → process default).
Returns
UINT32 packed image.
See also
bwunpack

◆ bwperim()

Value nk::image::bwperim ( const Value & BW,
int conn,
std::pmr::memory_resource * mr = nullptr )

Perimeter mask (BW2 = bwperim(BW, conn)).

A foreground pixel survives iff at least one of its conn-neighbours is background.

Parameters
BWBinary image.
connConnectivity (4 or 8).
mrMemory resource (nullptr → process default).
Returns
LOGICAL perimeter mask, same shape as BW.
See also
bwarea, bwboundaries

◆ bwpropfilt()

Value nk::image::bwpropfilt ( const Value & BW,
const Value & CC,
const Value & marker,
const std::string & attribute,
double p_min,
double p_max,
std::size_t keep_n,
bool keep_largest,
int conn,
std::pmr::memory_resource * mr = nullptr )

Filter connected components by attribute value (BW2 = bwpropfilt(BW, attrib, range_or_n, ...)).

Compute a region attribute (one of 17) for every connected component and return only those whose values satisfy the filter. The filter is either a [min max] numeric range or a top-n selector with keep_largest / keep_smallest. Optional marker image enables intensity-based attributes.

Supported attributes (case-insensitive):

  • "Area" : pixel count.
  • "Circularity" : 4·π·Area / Perimeter².
  • "ConvexArea" : pixel count inside convex hull.
  • "Eccentricity" : sqrt(1 − (b/a)²) from covariance.
  • "EquivDiameter" : 2·sqrt(Area / π).
  • "EulerNumber" : components - holes (8-conn default).
  • "Extent" : Area / (BBox.w · BBox.h).
  • "FilledArea" : pixel count after hole-fill.
  • "MajorAxisLength" : 2·2·sqrt(λ_max) of pixel covariance.
  • "MaxIntensity" : max(I[component]) (needs marker).
  • "MeanIntensity" : mean(I[component]) (needs marker).
  • "MinIntensity" : min(I[component]) (needs marker).
  • "MinorAxisLength" : 2·2·sqrt(λ_min).
  • "Orientation" : angle of major axis, in degrees, [-90, 90], sign-flipped y-axis.
  • "Perimeter" : Tomas-Holst weighted boundary count.
  • "PerimeterOld" : pre-2017 perimeter via 4-conn edges.
  • "Solidity" : Area / ConvexArea.
Parameters
BWLogical mask (Value::Empty when passing CC).
CCCC struct (Value::Empty when passing BW).
markerGrayscale marker image for intensity attribs (Value::Empty if not needed).
attributeOne of the 17 strings above.
p_min,p_maxIf keep_n == 0: filter by range [p_min, p_max].
keep_nTop-N selector (>0). Use 0 for range mode.
keep_largesttrue = largest-N, false = smallest-N (only matters when keep_n > 0).
conn4 or 8 (default 8).
mrMemory resource (nullptr → process default).
Returns
Filtered output: LOGICAL mask if BW input, CC struct (with filtered PixelIdxList) if CC input.
See also
bwconncomp, bwareafilt, cc2bw, labelmatrix

◆ bwselect()

std::tuple< Value, Value > nk::image::bwselect ( const Value & BW,
const Value & cols,
const Value & rows,
int conn,
std::pmr::memory_resource * mr = nullptr )

Select components by seed pixels ([BW2, idx] = bwselect(BW, cols, rows, conn)).

Returns the union of every connected component that contains at least one of the seed pixels (cols(k), rows(k)) (1-based).

Parameters
BWBinary image.
colsSeed column coordinates (1-based).
rowsSeed row coordinates (1-based).
connConnectivity (4 or 8).
mrMemory resource (nullptr → process default).
Returns
(BW2, idx) — selected mask + column of surviving 1-based linear pixel indices.

◆ bwtraceboundary()

Value nk::image::bwtraceboundary ( const Value & BW,
const Value & P,
const std::string & fstep,
int conn,
std::size_t m,
const std::string & dir,
std::pmr::memory_resource * mr = nullptr )

Trace object boundary in a binary image (B = bwtraceboundary(BW, P, fstep, conn, m, dir)).

Moore-Neighbor boundary tracing starting from foreground pixel P and initial search direction fstep. The trace walks the 8-connected (default) or 4-connected boundary and emits row/col coordinates.

fstep semantics. fstep defines the direction of the notional "previous" pixel as the OPPOSITE of fstep, so the search starts one position clockwise of that previous direction. This matches MATLAB R2025b behaviour even when fstep points into the object interior (the search just sweeps around to the first valid boundary neighbour).

Termination. Stops when the boundary loop closes (we revisit P after ≥ 1 step), when m pixels have been emitted, or when no neighbours exist (isolated pixel → returns [P; P]).

Reference: Moore-Neighbor tracing, Pavlidis 1982, Algorithms for Graphics and Image Processing, §7.5.

Parameters
BW2-D binary mask (logical or numeric non-zero).
P[row, col] 1-based starting boundary pixel.
fstep"N" / "NE" / "E" / "SE" / "S" / "SW" / "W" / "NW". For conn = 4, only "N" / "E" / "S" / "W".
conn8 (default) or 4.
mMaximum number of pixels to extract (std::numeric_limits<size_t>::max() for Inf).
dir"clockwise" (default) or "counterclockwise".
mrMemory resource (nullptr → process default).
Returns
Q × 2 DOUBLE matrix of [row, col] pixels.

◆ bwunpack()

Value nk::image::bwunpack ( const Value & BWP,
size_t M,
std::pmr::memory_resource * mr = nullptr )

Unpack a UINT32 binary image (BW = bwunpack(BWP, M)).

Inverse of bwpack. M is the original row count; pass 0 for rows(BWP) * 32.

Parameters
BWPUINT32 packed image.
MOriginal row count.
mrMemory resource (nullptr → process default).
Returns
LOGICAL image.
See also
bwpack

◆ cc2bw()

Value nk::image::cc2bw ( const Value & CC,
const Value & objects_to_keep,
std::pmr::memory_resource * mr = nullptr )

Reconstruct binary image from a bwconncomp struct (BW = cc2bw(CC, ...)).

Walks the PixelIdxList cell array and sets each listed pixel to true. With objects_to_keep empty, returns the union of all components (i.e. the original input mask). Otherwise only the selected components are rasterised.

objects_to_keep may be either:

  • A numeric vector of 1-based component indices (e.g. [1 3]).
  • A logical vector of length NumObjects (true = keep).
Parameters
CCStruct from bwconncomp.
objects_to_keepEmpty (= all) / numeric vector / logical vector. The vector orientation is ignored.
mrMemory resource (nullptr → process default).
Returns
LOGICAL mask sized like the source image.
See also
bwconncomp, labelmatrix, bwpropfilt

◆ checkerboard()

Value nk::image::checkerboard ( size_t side,
size_t M,
size_t N,
std::pmr::memory_resource * mr = nullptr )

Checkerboard test pattern (I = checkerboard(side, M, N)).

Produces a 2·M·side × 2·N·side DOUBLE image with alternating black / white squares; the right half is dimmed to grey (×0.7). Matches Octave-image's checkerboard.m. Pass 0 to any arg to use defaults: side = 10, M = 4, N = 4.

Parameters
sideSquare edge length in pixels (0 → default 10).
MVertical block count (0 → default 4).
NHorizontal block count (0 → default 4).
mrMemory resource (nullptr → process default).
Returns
2·M·side × 2·N·side checkerboard.

◆ chromadapt()

Value nk::image::chromadapt ( const Value & A,
const Value & illuminant,
const std::string & method,
const std::string & color_space,
std::pmr::memory_resource * mr = nullptr )

Chromatic adaptation for white-balance correction (B = chromadapt(A, illuminant, ...)).

Rebalances RGB image colours under a known scene illuminant by mapping responses from a "source" white-point (the illuminant) to CIE D65 (the destination assumed by sRGB and most other device-RGB encodings). Three documented methods:

  • Bradford (default; Lam 1985) — linear LMS-cone-space adaptation using the Bradford matrix. The CIECAM02 Bradford variant is the de-facto standard.
  • von Kries — Hunt-Pointer-Estevez sharpened LMS basis, simpler than Bradford but less perceptually uniform.
  • Simple — per-channel RGB scaling (no LMS transform). Fast but approximate; useful when the gamut transformation would clip badly.

Pipeline (Bradford / vonKries):

  1. Normalize illuminant: illuminant_xyz = rgb2xyz(illuminant); illuminant_xyz /= illuminant_xyz(2) (Y=1).
  2. Build adaptation matrix M_adapt = M⁻¹ · diag(M·whiteD65 / M·illuminant) · M where M is Bradford or von Kries.
  3. A_XYZ = rgb2xyz(A) (with D65 reference).
  4. B_XYZ = M_adapt · A_XYZ per pixel.
  5. B = xyz2rgb(B_XYZ) (D65 reference).

Pipeline (Simple):

  1. illuminant_xyz as above.
  2. illuminant_rgb = xyz2rgb(illuminant_xyz).
  3. B(:,:,c) = A(:,:,c) / illuminant_rgb(c) (per channel).

ColorSpace controls the gamma + primaries:

  • "srgb" (default) — sRGB primaries, sRGB piecewise gamma.
  • "adobe-rgb-1998" — Adobe primaries, γ ≈ 2.2.
  • "prophoto-rgb" — ProPhoto primaries with D50 white, piecewise gamma (γ = 1.8 + linear toe).
  • "linear-rgb" — sRGB primaries, identity gamma.

Output class matches input (uint8 / uint16 / single / double).

Parameters
ARGB image (H × W × 3, uint8/uint16/single/double).
illuminant3-element numeric vector in the same RGB colour space as A (NOT XYZ).
method"bradford" (def) / "vonkries" / "simple".
color_space"srgb" (def) / "adobe-rgb-1998" / "prophoto-rgb" / "linear-rgb".
mrMemory resource (nullptr → process default).
Returns
Adapted RGB image, same class as A.

References:

  • Lam, K.M. (1985). Metamerism and Colour Constancy. PhD thesis, University of Bradford.
  • Hunt, R. W. G. (2005). The Reproduction of Colour, 6th ed.

◆ cmap2gray()

Value nk::image::cmap2gray ( const Value & cmap,
std::pmr::memory_resource * mr = nullptr )

RGB colormap → grayscale colormap (gmap = cmap2gray(cmap)).

Each output row is [y y y] where y is the YIQ luminance 0.298936·R + 0.587043·G + 0.114021·B clipped to [0, 1].

Parameters
cmapN × 3 RGB colormap.
mrMemory resource (nullptr → process default).
Returns
N × 3 grayscale colormap.

◆ cmunique_xm()

std::pair< Value, Value > nk::image::cmunique_xm ( const Value & X,
const Value & MAP,
std::pmr::memory_resource * mr = nullptr )

Eliminate duplicate colors in colormap; convert grayscale or RGB to indexed ([Y, newmap] = cmunique(...)).

Three input signatures:

  • cmunique(X, MAP) — quantise MAP to 1/1024 and drop duplicate rows; rebuild X to reference the compressed map.
  • cmunique(RGB) — treat each pixel as a distinct colour, then run the dedup pass.
  • cmunique(I) — treat each intensity as the grey triplet [I I I], then dedup.

The output index Y is uint8 if newmap has ≤ 256 rows and double otherwise (matches MATLAB R2025b).

Parameters
XIndexed image (uint8 / uint16 / double / single).
MAPN × 3 double colormap.
mrMemory resource (nullptr → process default).
Returns
Pair (Y, newmap) with the smallest equivalent colormap.

◆ col2im()

Value nk::image::col2im ( const Value & B,
int m,
int n,
int mm,
int nn,
const std::string & block_type,
std::pmr::memory_resource * mr = nullptr )

Inverse of im2col (A = col2im(B, [m n], [mm nn], block_type)).

  • "sliding" expects B to be 1 × (mm−m+1)·(nn−n+1) (a row of filter responses); reshapes to (mm−m+1) × (nn−n+1).
  • "distinct" expects B to be m·n × ⌈mm/m⌉·⌈nn/n⌉; rebuilds the mm × nn image, dropping the zero-pad rim that im2col added on the right / bottom edges.
Parameters
BNeighbourhood-column matrix from im2col.
mWindow row count used at packing time.
nWindow column count used at packing time.
mmTarget image row count.
nnTarget image column count.
block_type"sliding" (default) or "distinct".
mrMemory resource (nullptr → process default).
Returns
Reconstructed mm × nn image.
See also
im2col

◆ colfilt()

Value nk::image::colfilt ( const Value & A,
std::size_t m,
std::size_t n,
const std::string & block_type,
FnHandle fun,
bool indexed,
std::pmr::memory_resource * mr = nullptr )

Column-wise neighbourhood operation (B = colfilt(A, [m n], block_type, fun)).

Rearranges either every sliding m × n window (block_type = "sliding") or every distinct (non-overlapping) m × n block (block_type = "distinct") of A into columns of a temporary matrix, calls fun on that matrix, then rearranges the result back. Faster than nlfilter for batch-compatible kernels since fun is invoked once on a wide matrix.

Sliding mode. A is zero-padded (or one-padded under indexed = true for double/single). The matrix X passed to fun is m·n × (rows·cols) (one column per centre pixel). fun(X) must return a 1 × (rows·cols) row vector, reshaped back into the original A's shape.

Distinct mode. A is zero-padded (or one-padded under indexed = true) up to the next multiple of [m n]. X is m·n × (nb_rows·nb_cols) (one column per distinct block). fun(X) must return a matrix of the SAME shape; the columns are unpacked back into blocks, then the padded image is cropped to the original size(A).

The optional [mblock nblock] MATLAB argument is a memory-only optimisation (the docs note it does not change the result); the engine adapter accepts it but ignores it.

Output class equals the class of fun()'s return value (matches MATLAB R2025b).

Parameters
engEngine used to dispatch fun.
AInput image.
mBlock rows.
nBlock cols.
block_type"sliding" or "distinct" (case-insensitive, abbreviated by leading character).
funCallback invoked on the m*n × Ncol column matrix; returns the per-column result. (Engine adapter binds it to the user handle; core-free.)
indexedtrue ⇒ 'indexed' padding (1 for floats, 0 otherwise).
mrMemory resource (nullptr → process default).
Returns
Filtered image (same H × W as A in sliding; same H × W as A in distinct, after cropping).

◆ colorangle()

Value nk::image::colorangle ( const Value & rgb1,
const Value & rgb2,
std::pmr::memory_resource * mr = nullptr )

Angle between two RGB colours (theta = colorangle(rgb1, rgb2)).

rad2deg(acos(dot(rgb1, rgb2) / (|rgb1| · |rgb2|))). Inputs may be 3-element vectors or N × 3 matrices; broadcasting between a single colour and a stack is supported. Returns 0 when both colours are zero, NaN when only one is zero. Cosine is clamped to [-1, 1].

Parameters
rgb1First RGB.
rgb2Second RGB.
mrMemory resource (nullptr → process default).
Returns
Angle(s) in degrees.

◆ colorgradient()

Value nk::image::colorgradient ( const Value & C,
const Value & w,
int n,
std::pmr::memory_resource * mr = nullptr )

Smooth colormap through K anchor colours (M = colorgradient(C, w, n)).

Per-segment linspace between consecutive rows of C, with relative segment weights w (length K - 1, default ones). Output is DOUBLE N × 3.

Parameters
CK × 3 anchor RGB colours.
wSegment weights vector (or Value::Empty → ones).
nOutput rows (default 64).
mrMemory resource (nullptr → process default).
Returns
N × 3 colormap.

◆ contrast()

Value nk::image::contrast ( const Value & x,
int m,
std::pmr::memory_resource * mr = nullptr )

Histogram-equalising gray colormap (cmap = contrast(x, m)).

Algorithm: scale x to [0, m-1] integers, concat with [0..m], sort, return rising-edge positions divided by their max as a length-≈m gray colormap. Three identical columns.

Parameters
xInput image used to derive the histogram.
mTarget colormap length (default 64 in adapter).
mrMemory resource (nullptr → process default).
Returns
≈m × 3 gray colormap.

◆ convmtx2()

Value nk::image::convmtx2 ( const Value & h,
int m,
int n,
std::pmr::memory_resource * mr = nullptr )

2-D convolution matrix (T = convmtx2(h, m, n)).

Builds the dense matrix T for 2-D 'full' convolution. Shape: (m+M-1)·(n+N-1) × m·n where h is M × N. Multiplying T by vec(I) (column-major) produces vec(conv2(I, h, 'full')). The result is returned dense (nk has no sparse storage yet). Output type is double regardless of input class.

Parameters
hConvolution kernel (M × N).
mImage row count.
nImage column count.
mrMemory resource (nullptr → process default).
Returns
Dense convolution matrix, DOUBLE.

◆ cool_cmap()

Value nk::image::cool_cmap ( int n,
std::pmr::memory_resource * mr = nullptr )

Cyan → magenta colormap (map = cool(n)).

r = (0:n-1)/(n-1), g = 1 - r, b = 1.

Parameters
nRow count.
mrMemory resource.
Returns
n × 3 colormap.

◆ copper_cmap()

Value nk::image::copper_cmap ( int n,
std::pmr::memory_resource * mr = nullptr )

Copper-tinted colormap (map = copper(n)).

x = (0:n-1)/(n-1); r = min(5/4·x, 1), g = 0.7812·x, b = 0.4975·x.

Parameters
nRow count.
mrMemory resource.
Returns
n × 3 colormap.

◆ corner()

Value nk::image::corner ( const Value & I,
const std::string & method,
int maxN,
double quality_level,
double sensitivity,
const Value & filter_coef,
std::pmr::memory_resource * mr = nullptr )

Detect corner points (C = corner(I, ...)).

Wraps cornermetric: keep its local maxima above quality_level · max(metric), take each connected peak's centroid, sort by strength (descending), and return up to maxN integer [x y] = [col row] coordinates (one row per corner). Equal-strength peaks tie-break by ascending column-major index (MATLAB find order); the image border is excluded naturally (its metric is ≤ 0 < threshold).

Parameters
I2-D grayscale or logical image.
method"Harris" (default) or "MinimumEigenvalue".
maxNMaximum number of corners (default 200; <0 = all).
quality_levelThreshold fraction of the peak metric (default 0.01).
sensitivityHarris k ∈ (0, 0.25) (default 0.04); ignored for MinEig.
filter_coefSmoothing filter (empty → default 5-tap Gaussian).
mrMemory resource (nullptr → process default).
Returns
K × 2 DOUBLE matrix of [x y] corner coordinates.
See also
cornermetric

◆ cornermetric()

Value nk::image::cornermetric ( const Value & I,
const std::string & method,
double sensitivity_factor,
const Value & filter_coef,
std::pmr::memory_resource * mr = nullptr )

Corner metric matrix (C = cornermetric(I, method, ...)).

Computes per-pixel corner-likelihood using the Harris (default) or Shi–Tomasi ("MinimumEigenvalue") detector. Larger output values indicate stronger corner features.

Algorithm (Harris 1988, Shi-Tomasi 1994): Dx = imfilter(I, [-1 0 1], 'replicate', 'conv') Dy = imfilter(I, [-1 0 1]', 'replicate', 'conv') trim 1-pixel border on Dx, Dy A = Dx², B = Dy², C = Dx·Dy smooth A, B, C with W = filter_coef · filter_coef' (full conv) crop back to image size Harris: cornerness = A·B − C² − k·(A+B)² MinimumEigenvalue: cornerness = ((A+B) − √((A−B)² + 4·C²)) / 2

Default filter_coef = fspecial('gaussian', [5 1], 1.5) = [0.1201, 0.2339, 0.2921, 0.2339, 0.1201]. sensitivity_factor k ∈ (0, 0.25) applies only to the Harris method (default 0.04).

References: [1] Harris & Stephens, "A Combined Corner and Edge Detector", 4th Alvey Vision Conference, 1988. [2] Shi & Tomasi, "Good Features to Track", CVPR 1994.

Output class is DOUBLE regardless of input class. Image is internally promoted via im2double (uint8/uint16/single/etc.).

Parameters
I2-D grayscale or logical image.
method"Harris" (default) or "MinimumEigenvalue".
sensitivity_factork ∈ (0, 0.25); ignored for MinEig.
filter_coef1-D smoothing filter coefficients (length ≥ 3, odd). Empty → default 5-tap Gaussian.
mrMemory resource (nullptr → process default).
Returns
H × W DOUBLE corner-metric image.

◆ corr2()

Value nk::image::corr2 ( const Value & A,
const Value & B,
std::pmr::memory_resource * mr = nullptr )

2-D correlation coefficient (r = corr2(A, B)).

Pearson r computed over all elements (flattened). Class is converted to DOUBLE for the computation; A and B must have the same numel.

Parameters
AFirst image.
BSecond image (same numel).
mrMemory resource (nullptr → process default).
Returns
Pearson correlation scalar.

◆ dct2()

Value nk::image::dct2 ( const Value & A,
std::pmr::memory_resource * mr = nullptr )

2-D Type-II orthonormal DCT (B = dct2(A)).

Separable: dct2(A) == dct(dct(A).').'. Internally applies the 1-D signal::dct along columns first, then along rows.

Parameters
A2-D real matrix.
mrMemory resource (nullptr → process default).
Returns
M × N DCT coefficients of the same size as A.
See also
idct2, dctmtx

◆ dctmtx()

Value nk::image::dctmtx ( double N,
std::pmr::memory_resource * mr = nullptr )

N × N DCT-II transform matrix (D = dctmtx(N)).

Returns an orthonormal matrix D (D' · D == I) such that D * A applies the 1-D DCT to each column of A. Useful for block-DCT pipelines.

Parameters
NBlock size.
mrMemory resource (nullptr → process default).
Returns
N × N orthonormal matrix.
See also
dct2

◆ deconvreg()

DeconvregResult nk::image::deconvreg ( const Value & I,
const Value & PSF,
double np,
double lo,
double hi,
const Value & regop,
std::pmr::memory_resource * mr = nullptr )

Tikhonov-regularized deconvolution ([J, LAGRA] = deconvreg(I, PSF, NP, ...)).

Solves the constrained least-squares restoration problem.

Parameters
I2-D blurred image.
PSFPoint-spread function.
npNoise power estimate.
loLower bound for Lagrange multiplier search.
hiUpper bound for Lagrange multiplier search.
regopCustom regularization operator (or empty for Laplacian).
mrMemory resource for output allocation.
Returns
DeconvregResult containing restored image J and Lagrange multiplier lagra.

◆ deconvwnr() [1/2]

Value nk::image::deconvwnr ( const Value & I,
const Value & PSF,
const Value & ncorr,
const Value & icorr,
std::pmr::memory_resource * mr = nullptr )

Wiener deconvolution using autocorrelation functions (J = deconvwnr(I, PSF, NCORR, ICORR)).

Parameters
IBlurred input image.
PSFPoint-spread function.
ncorrAutocorrelation function of noise.
icorrAutocorrelation function of original image.
mrMemory resource for output allocation.
Returns
Deblurred image.

◆ deconvwnr() [2/2]

Value nk::image::deconvwnr ( const Value & I,
const Value & PSF,
double nsr,
std::pmr::memory_resource * mr = nullptr )

Wiener deconvolution (J = deconvwnr(I, PSF, NSR) / deconvwnr(I, PSF, NCORR, ICORR)).

Deblurs image I assuming a known point-spread function PSF. The Wiener inverse filter G(k) = conj(H(k)) / (|H(k)|^2 + S_u/S_x) minimises the mean-square error between the estimated and the true images (Gonzalez & Woods, Digital Image Processing). H(k) is the OTF returned by psf2otf at size(I).

Argument forms:

  • (I, PSF, nsr_scalar) — scalar NSR (S_u/S_x); 0 produces the ideal inverse filter (subject to the small sqrt(eps) denominator floor).
  • (I, PSF, ncorr, icorr) — scalar noise / signal powers; equivalent to NSR = ncorr / icorr.
  • Array NCORR / ICORR (autocorrelation functions of the same size as I) are also supported: each is FFT'd to a power spectrum first; the 1-D extrapolation form of MATLAB's powerSpectrumFromACF is not implemented and throws.

Output class equals input class (uint8/uint16 are scaled by the class range and saturating-cast at the end). Real inputs produce a real output (the tiny imaginary part of the IFFT is discarded).

Parameters
I2-D or 3-D blurred image (any numeric class).
PSFPoint-spread function (real, any size ≤ I).
nsrNoise-to-signal power ratio (default 0).
mrMemory resource (nullptr → process default).
Returns
Deblurred image, same class and shape as I.

◆ deltaE()

Value nk::image::deltaE ( const Value & I1,
const Value & I2,
bool isInputLab,
std::pmr::memory_resource * mr = nullptr )

CIE76 colour difference (delE = deltaE(I1, I2, isInputLab)).

Default treats inputs as RGB and converts to L*a*b* internally; pass isInputLab = true to skip the conversion. Result is sqrt(sum((Lab1 - Lab2).^2, 3)) — Euclidean distance in CIELAB. Class promotion: any DOUBLE input → DOUBLE output, else SINGLE.

Parameters
I1First image (RGB by default, or Lab).
I2Second image (matching class / shape).
isInputLabWhen true, inputs are Lab; skip conversion.
mrMemory resource (nullptr → process default).
Returns
H × W (or N × 1) deltaE.

◆ demosaic()

Value nk::image::demosaic ( const Value & I,
const std::string & sensorAlignment,
int bitsPerSample = 0,
std::pmr::memory_resource * mr = nullptr )

Convert a Bayer-encoded mosaic to a truecolor RGB image (RGB = demosaic(I, sensorAlignment, BitsPerSample=bps)).

Implements the high-quality linear interpolation of Malvar, He, and Cutler (ICASSP 2004): five 5×5 integer kernels (G-at-RB, R/B-at-G-same-row, R/B-at-G-diff-row, R-at-B / B-at-R) reconstruct the missing channels at each pixel. At the sensor positions themselves the raw mosaic value is returned unchanged.

Boundary handling reflects through the FIRST pixel (k=-1 → orig(1), k=N → orig(N-2)) so the mirrored neighbourhood preserves the Bayer pattern — this differs from imfilter's standard symmetric mode and matches MATLAB R2025b.

Parameters
IBayer mosaic (M×N, uint8 / uint16 / uint32). M, N must both be even.
sensorAlignmentOne of "rggb", "bggr", "grbg", "gbrg" — colour of the (1,1) pixel and its right neighbour.
bitsPerSampleOptional bits-per-sample for clamping the output (e.g. 12 for 12-bit data in a uint16 container). 0 means use the class maximum (default).
mrMemory resource (nullptr → process default).
Returns
M×N×3 truecolor image of the input class.

References:

  • Malvar, He, Cutler. "High-Quality Linear Interpolation for Demosaicing of Bayer-Patterned Color Images", IEEE ICASSP 2004.

◆ dice()

Value nk::image::dice ( const Value & A,
const Value & B,
std::pmr::memory_resource * mr = nullptr )

Sørensen–Dice similarity coefficient (d = dice(BW1, BW2)).

d = 2·|A ∩ B| / (|A| + |B|). Operates on binary masks; any non-zero pixel counts as foreground. Returns 1 when both masks are empty (degenerate convention).

Parameters
ASame-sized binary mask.
BSame-sized binary mask.
mrMemory resource (nullptr → process default).
Returns
Scalar in [0, 1].
See also
jaccard

◆ edge()

Value nk::image::edge ( const Value & I,
const std::string & method,
double thresh_lo,
double thresh_hi,
std::pmr::memory_resource * mr = nullptr )

Binary edge map (BW = edge(I, method, thresh_lo, thresh_hi)).

Detector dispatch:

method description
"sobel" (d) gradient magnitude > thresh
"prewitt" gradient magnitude > thresh
"roberts" 2×2 cross-difference
"canny" Canny edge detector (uses both thresholds)
"log" Laplacian of Gaussian, zero crossings ± thresh
"zerocross" zero crossings of a user kernel (not yet wired)

thresh_lo / thresh_hi accept NaN to request the auto-pick heuristic (30 % of max gradient for the simple detectors; Otsu / fraction-based for Canny).

Parameters
IInput image.
methodDetector name.
thresh_loLower threshold or NaN.
thresh_hiUpper threshold (Canny) or NaN.
mrMemory resource (nullptr → process default).
Returns
Logical edge map.
See also
imgradient

◆ edgetaper()

Value nk::image::edgetaper ( const Value & I,
const Value & PSF,
std::pmr::memory_resource * mr = nullptr )

Taper image edges via blur (J = edgetaper(I, PSF)).

Reduces FFT ringing in deblurring methods that use the DFT (deconvwnr, deconvreg, deconvlucy). The output is a weighted blend of I and imfilter(I, PSF, 'circular'): J = alpha .* I + (1 − alpha) .* blurredI where alpha is built from per-dimension PSF projections' autocorrelation, equalling 1 in the interior and tapering to 0 at the edges over a width controlled by PSF.

Algorithm (transliterated from MATLAB R2025b edgetaper.m):

  1. For each non-singleton dim n: proj = sum(PSF along all other dims) Z = |fft(proj, sizeI(n) - 1)|^2 beta_n = real(ifft(Z)) beta_n = [beta_n beta_n(1)] / max(beta_n) (length sizeI(n))
  2. alpha = outer-product of (1 − beta_n) across the non-singleton dims.
  3. blurredI = real(ifftn(fftn(I) .* psf2otf(PSF, sizeI))).
  4. J = alpha .* I + (1 − alpha) .* blurredI, clipped to [min(I), max(I)].
  5. Cast back to class(I) for integer types.

Constraints: PSF cannot exceed half of I in any dimension. PSF must contain at least one non-zero element. 2-D and 1-D inputs supported (the 3-D-and-up form is rarely used but the MATLAB source documents it via the same algorithm; we throw a clear error if I is 3-D so the caller knows to slice).

Parameters
IInput image.
PSFPoint-spread function (any size ≤ size(I)/2).
mrMemory resource (nullptr → process default).
Returns
Tapered image, same class and shape as I.

◆ entropy()

Value nk::image::entropy ( const Value & I,
int nbins,
std::pmr::memory_resource * mr = nullptr )

Shannon entropy of the image histogram (H = entropy(I, nbins)).

In bits. For non-logical images the image is first converted to uint8 with 256 bins by default; logical images use 2 bins. Zero counts are skipped before the log₂ sum.

Parameters
IInput image.
nbinsHistogram bin count.
mrMemory resource (nullptr → process default).
Returns
Scalar entropy in bits.
See also
entropyfilt

◆ entropyfilt()

Value nk::image::entropyfilt ( const Value & I,
const Value & domain,
std::pmr::memory_resource * mr = nullptr )

Local Shannon entropy (B = entropyfilt(I, domain)).

Computed in bits. 256-bin histogram for non-logical inputs (uint8 / im2uint8 cast), 2 bins for logical. Default domain = ones(9). Symmetric boundary.

Parameters
IInput image.
domainNeighbourhood mask.
mrMemory resource (nullptr → process default).
Returns
DOUBLE entropy image, same shape as I.
See also
stdfilt, rangefilt

◆ fchcode()

Value nk::image::fchcode ( const Value & bound,
std::pmr::memory_resource * mr = nullptr )

Freeman 8-direction chain code (fcc = fchcode(bound)).

Encodes a closed K×2 boundary (rows / cols) as a sequence of 8-direction codes. Direction map:

3 2 1
4 . 0
5 6 7

Returns a struct with fields:

  • x0y0 — 1×2 start point (matches bound(1, :)).
  • fcc — 1×K direction codes.
  • diff — 1×K mod-8 first-difference (cyclic).

If the boundary doesn't already close on itself, the first point is appended automatically.

Parameters
boundBoundary K×2 matrix (rows, cols).
mrMemory resource (nullptr → process default).
Returns
Struct with x0y0, fcc, diff fields.
See also
bwboundaries

◆ fftconv2()

Value nk::image::fftconv2 ( const Value & A,
const Value & B,
const std::string & shape,
std::pmr::memory_resource * mr = nullptr )

2-D convolution via FFT (Y = fftconv2(A, B, shape)).

Faster than direct conv2 for large inputs, less accurate. Output is COMPLEX (a tiny imaginary part appears even for real inputs).

Parameters
AFirst input.
BSecond input.
shape"full" (default), "same", or "valid".
mrMemory resource (nullptr → process default).
Returns
Convolution result.
Exceptions
ErrorUnknown shape (m:fftconv2:shape).

◆ fibermetric()

Value nk::image::fibermetric ( const Value & I,
const std::vector< double > & thickness,
double structure_sensitivity,
bool bright_polarity,
std::pmr::memory_resource * mr = nullptr )

Multi-scale Frangi vesselness filter (J = fibermetric(I, thickness, ...)).

Enhances elongated / tubular structures (vessels, fibres, filaments) at user-specified scales. For each thickness t_i:

  • σ_i = t_i / 6.
  • Gaussian-smooth I with FilterSize = 2·ceil(3σ_i)+1.
  • Compute Hessian (3 elements for 2-D, 6 for 3-D) by central finite differences.
  • Compute Hessian eigenvalues.
  • Apply Frangi 1998 vesselness:
    • 2-D: λ₁, λ₂ with |λ₁| ≤ |λ₂|. Bright structures need λ₂ < 0; dark need λ₂ > 0 (else vesselness = 0). Rβ = λ₁/λ₂, S = sqrt(λ₁² + λ₂²). V = exp(-Rβ²/(2·β²)) · (1 - exp(-S²/(2·c²))), with β = 0.5 (fixed).
    • 3-D: λ₁, λ₂, λ₃ with |λ₁| ≤ |λ₂| ≤ |λ₃|. Bright need λ₂ < 0 && λ₃ < 0; dark need both > 0. Rα = |λ₂|/|λ₃| (plate-vs-line), Rβ = |λ₁|/sqrt(|λ₂·λ₃|) (blobness), S² = λ₁² + λ₂² + λ₃². V = (1 - exp(-Rα²/(2α²))) · exp(-Rβ²/(2β²)) · (1 - exp(-S²/(2c²))), with α = β = 0.5 (fixed).

Per-pixel max over all thickness scales.

c (structure_sensitivity) defaults to diff(getrangefromclass(I)) / 100 (e.g. 2.55 for uint8, 655.35 for uint16, 0.01 for single/double). Pass -1.0 for the class default.

bright_polarity = true (default) detects light-on-dark structures. false detects dark-on-light.

Input class: uint8, uint16, uint32, int8, int16, int32, single, double 2-D or 3-D image (all dimensions ≥ 2). Output class: single for everything except double input, which preserves double.

References: Frangi, A. F., Niessen, W. J., Vincken, K. L., Viergever, M. A. (1998). Multiscale vessel enhancement filtering. MICCAI 1998.

Parameters
IGrayscale 2-D image or 3-D volume.
thicknessVector of thickness scales (default = [4 6 8 10 12 14] if empty).
structure_sensitivityc (-1 = class default).
bright_polaritytrue = bright (default).
mrMemory resource (nullptr → default).
Returns
Vesselness response, same shape as I.

◆ flag_cmap()

Value nk::image::flag_cmap ( int n,
std::pmr::memory_resource * mr = nullptr )

Cyclic red/white/blue/black colormap (map = flag(n)).

Cycles [1 0 0; 1 1 1; 0 0 1; 0 0 0].

Parameters
nRow count.
mrMemory resource.
Returns
n × 3 colormap.

◆ freqz2()

std::tuple< Value, Value, Value > nk::image::freqz2 ( const Value & h,
size_t M,
size_t N,
std::pmr::memory_resource * mr = nullptr )

2-D frequency response of a filter ([H, f1, f2] = freqz2(h, M, N)).

Evaluates h on a freqspace-style M × N grid (default 64×64). H[i, j] = Σ_{p, q} h[p, q]·exp(−iπ(f1[i]·p + f2[j]·q)) where f1 / f2 are the row/column frequency vectors from the freqspace grid.

Parameters
hFilter kernel.
MNumber of frequency samples along rows.
NNumber of frequency samples along cols.
mrMemory resource (nullptr → process default).
Returns
Tuple (H, f1, f2).

◆ fsamp2()

Value nk::image::fsamp2 ( const Value & Hd,
const Value & f1,
const Value & f2,
const std::vector< std::size_t > & siz,
std::pmr::memory_resource * mr = nullptr )

2-D FIR filter design via frequency sampling (h = fsamp2(Hd)).

Computes the inverse DFT of the desired frequency response Hd (assumed sampled on the equally-spaced freqspace grid in [-1, 1]), centred and rotated for use with filter2.

Pipeline (uniform-spacing case, matches MATLAB R2025b fsamp2.m):

  1. hd_shifted = ifftshift(Hd).
  2. h_complex = fftshift(ifft2(hd_shifted)).
  3. If max(abs(imag(h))) < sqrt(eps): h = real(h).
  4. h = rot90(h, 2) — for use with filter2.

The non-uniform case fsamp2(f1, f2, Hd, [m n]) (least-squares fit at arbitrary frequency samples) is not yet implemented — pass f1 / f2 as Value::Empty and siz as {} for the uniform case. Calling with non-empty f1 / f2 throws.

Reference: Lim, J. S. (1990). Two-Dimensional Signal and Image Processing, Prentice-Hall, pp. 213–217.

Parameters
HdDesired frequency response (M × N).
f1Frequency samples along x (empty for uniform spacing).
f2Frequency samples along y (empty for uniform spacing).
sizOutput filter size (empty for uniform spacing).
mrMemory resource (nullptr → process default).
Returns
DOUBLE filter, same shape as Hd (uniform) or [m n].

◆ fspecial()

Value nk::image::fspecial ( const std::string & type,
const std::vector< double > & params,
std::pmr::memory_resource * mr = nullptr )

Build a 2-D filter kernel by name (h = fspecial(type, params)).

Supported types: "average", "gaussian", "laplacian", "log", "sobel", "prewitt", "disk". The params interpretation depends on type (e.g. "gaussian" takes [hsize, sigma]).

Parameters
typeKernel name (see list above).
paramsType-specific parameter vector.
mrMemory resource (nullptr → process default).
Returns
DOUBLE kernel matrix.
Exceptions
ErrorUnknown type or wrong-shape params.

◆ fspecial3()

Value nk::image::fspecial3 ( const std::string & type,
const Value & a1,
const Value & a2,
std::pmr::memory_resource * mr = nullptr )

Build a predefined 3-D filter kernel (h = fspecial3(type, ...)).

Supported type values and their positional arguments (a1, a2):

type a1 a2 output
average hsize ([5 5 5]) — ones/prod
gaussian hsize ([5 5 5]) sigma (1) normalised, Σ=1
log hsize ([5 5 5]) sigma (1) ∇²G, zero-mean
ellipsoid semiaxes (5) — mask/count
laplacian gamma1 (0) gamma2(0) 3×3×3, Σ=0
prewitt direction ("X") — 3×3×3 gradient
sobel direction ("X") — 3×3×3 gradient

hsize / semiaxes / sigma accept a scalar (applied to all three axes) or a 3-element [row col page] vector. For ellipsoid the output size is 2·ceil(semiaxes)+1 per axis and the kernel is the integer-grid mask {(Δr/a)²+(Δc/b)²+(Δp/c)² ≤ 1} normalised by voxel count. For laplacian, gamma1 weights the 12 edge neighbours and gamma2 the 8 corner neighbours; both must be ≥ 0 with gamma1+gamma2 ≤ 1. direction is "X" (cols), "Y" (rows), or "Z" (pages).

Reference: J. Lim, Two-Dimensional Signal and Image Processing, Prentice Hall, 1990 (LoG and gradient kernels).

Parameters
typeKernel name (see table).
a1First type-specific argument (Value::Empty → default).
a2Second type-specific argument (Value::Empty → default).
mrMemory resource (nullptr → process default).
Returns
DOUBLE 3-D kernel.
Exceptions
ErrorUnknown type, bad shape, or invalid gamma.
See also
fspecial, imboxfilt3, imgaussfilt3

◆ ftrans2()

Value nk::image::ftrans2 ( const Value & b,
const Value & t,
std::pmr::memory_resource * mr = nullptr )

2-D FIR filter via 1-D → 2-D frequency transformation (h = ftrans2(b, t)).

Maps a 1-D zero-phase FIR b (type-I, odd-length, symmetric) into a 2-D filter h via the polynomial transform t. With t empty, uses the McClellan transformation t = [1 2 1; 2 -4 2; 1 2 1]/8 (approximately circularly symmetric).

Algorithm (Lim 1990, pp. 217–219): for b = a₀ + sum_n 2·aₙ·cos(nω) the 2-D filter is h = sum_n aₙ · Tₙ(t) where Tₙ is the n-th Chebyshev polynomial of the first kind. Computed recursively via T₀ = 1, T₁ = t, Tₙ₊₁ = 2·conv2(t, Tₙ) − Tₙ₋₁.

Parameters
b1-D FIR coefficients (must be odd-length, symmetric).
tTransform matrix (Value::Empty → default McClellan).
mrMemory resource (nullptr → process default).
Returns
DOUBLE 2-D filter of size ((M_t-1)·(Q_b-1)/2 + 1) × ((N_t-1)·(Q_b-1)/2 + 1).

◆ fwind1()

Value nk::image::fwind1 ( const Value & Hd,
const Value & win1,
const Value & win2,
std::pmr::memory_resource * mr = nullptr )

2-D FIR filter via 1-D window method (h = fwind1(Hd, win1[, win2])).

Uses the inverse DFT (fsamp2) of Hd and multiplies by an approximately circularly-symmetric or separable 2-D window built from one or two 1-D windows.

With one 1-D window win (Huang's method): build the 2-D circular window by linearly interpolating win along the radial coordinate r = sqrt(x² + y²), then truncate to the unit disc.

With two 1-D windows win1, win2: separable outer product.

Parameters
HdDesired frequency response.
win1Primary 1-D window (length N).
win2Optional second 1-D window (separable); empty → Huang's method.
mrMemory resource (nullptr → process default).
Returns
DOUBLE 2-D filter, length(win1) × length(win1) for Huang, length(win2) × length(win1) for separable.

◆ fwind2()

Value nk::image::fwind2 ( const Value & Hd,
const Value & W,
std::pmr::memory_resource * mr = nullptr )

2-D FIR filter via 2-D window method (h = fwind2(Hd, W)).

Computes h = fsamp2(Hd) .* W. If Hd is smaller than W, it is bilinearly interpolated to match (this branch requires freqspace + interp2).

Parameters
HdDesired frequency response.
W2-D window, same size as final filter.
mrMemory resource (nullptr → process default).
Returns
DOUBLE 2-D filter, same size as W.

◆ getrangefromclass()

Value nk::image::getrangefromclass ( const Value & I,
std::pmr::memory_resource * mr = nullptr )

Class display range (r = getrangefromclass(I)).

Returns the conventional [min, max] for the class of I:

  • integer types: intmin / intmax of the class.
  • LOGICAL, SINGLE, DOUBLE: [0, 1].
Parameters
IInput image.
mrMemory resource (nullptr → process default).
Returns
1 × 2 DOUBLE row.

◆ gradientweight()

Value nk::image::gradientweight ( const Value & I,
double sigma_x,
double sigma_y,
double rolloff_factor,
double weight_cutoff,
std::pmr::memory_resource * mr = nullptr )

Pixel weights from image gradient magnitude (W = gradientweight(I [, sigma], 'RolloffFactor', P, 'WeightCutoff', K)).

Companion to graydiffweight for Fast-Marching-Method based segmentation (imsegfmm): output is large in smooth regions and small on edges, so the FMM front travels fast inside objects and stalls at boundaries.

Algorithm (transliterated from MATLAB R2025b images.internal.imgradientdog + gradientweight.m):

  1. Derivative-of-Gaussian (DoG) kernels of radius r = ceil(2σ) along each axis: hx(x) = -x · exp(-x²/(2σ²)) for x ∈ {-r,...,r}, normalised so the positive half (hx(1..r)) sums to 1. hy is the column-transpose with σ_y.
  2. Gx = imfilter(I, hx, 'replicate'), Gy = imfilter(I, hy, 'replicate'), Gmag = hypot(Gx, Gy).
  3. W = imlinscale(Gmag, [0, 1]) (linear rescale).
  4. W = W .^ (1 / RolloffFactor), W = (1 − W) ./ (1 + W).
  5. W(W < WeightCutoff) = 1e-3 (FMM stop floor).

σ may be a scalar (replicated per dim) or a 2-element vector [σ_x, σ_y]. Constant-image fast-path returns ones(size(I)).

Output class: single if I is single, else double (matches MATLAB R2025b — uint8/int8/etc → double).

2-D inputs only (3-D throws — MATLAB calls imgradientdog3 for volumes; not yet ported).

References: Gonzalez & Woods, Digital Image Processing, §10 (edge detection via gradient magnitude); Sethian, Level Set Methods and Fast Marching Methods, Cambridge 1999 (FMM weights).

Parameters
I2-D grayscale image (any numeric class).
sigma_xDoG σ along x (cols). Must be > 0.
sigma_yDoG σ along y (rows). Must be > 0.
rolloff_factor> 0. Default 3. Controls falloff steepness.
weight_cutoff∈ [1e-3, 1]. Default 0.25. Threshold floor.
mrMemory resource (nullptr → process default).
Returns
Weight array, same H×W as I.

◆ gray2ind()

std::tuple< Value, Value > nk::image::gray2ind ( const Value & I,
int n,
std::pmr::memory_resource * mr = nullptr )

Grayscale → indexed ([ind, map] = gray2ind(I, n)).

Quantises I into n bins. Float input must be in [0, 1]; integer input is rescaled. LOGICAL default n = 2; otherwise n = 64. Output ind is UINT8 if n <= 256, else UINT16. map is the linear gray(n) colormap (n × 3).

Parameters
IInput grayscale image.
nBin count.
mrMemory resource (nullptr → process default).
Returns
(ind, map) pair.
See also
ind2gray, ind2rgb

◆ gray_cmap()

Value nk::image::gray_cmap ( int n,
std::pmr::memory_resource * mr = nullptr )

Grayscale colormap (map = gray(n)).

gr = (0:n-1)/(n-1) repeated across all 3 channels.

Parameters
nRow count.
mrMemory resource.
Returns
n × 3 colormap.

◆ graycomatrix()

Value nk::image::graycomatrix ( const Value & I,
int numLevels,
int offR,
int offC,
double gLow,
double gHigh,
bool symmetric,
std::pmr::memory_resource * mr = nullptr )

Gray-level co-occurrence matrix (G = graycomatrix(I, ...)).

Quantises I into numLevels bins over [gLow, gHigh], then for every pixel pair (p, q = p + (offR, offC)) increments G[q_level, p_level].

Note: the GLCM convention is that rows index the level of the first pixel and columns index the offset pixel. When symmetric is true, the reverse transition G[j, i] is also counted (the 'Symmetric' option).

Parameters
I2-D grayscale image (any numeric class).
numLevelsNumber of quantisation bins (typical 8 for uint8, 2 for logical).
offRRow offset of the second pixel.
offCColumn offset of the second pixel.
gLowLower bound of GrayLimits (class min if NaN).
gHighUpper bound of GrayLimits (class max if NaN).
symmetricWhen true, also count the reverse transition.
mrMemory resource (nullptr → process default).
Returns
numLevels × numLevels double matrix of counts.

KNOWN GAPS:

  • Multiple offsets in one call (would need a 3-D GLCM); pass each offset separately for now.
  • 'NumLevels' auto-default for floating-point inputs uses a conservative 8 instead of 64.
See also
graycoprops

◆ grayconnected()

Value nk::image::grayconnected ( const Value & I,
int row,
int col,
double tol,
std::pmr::memory_resource * mr = nullptr )

Flood-fill region from a seed pixel (BW = grayconnected(I, row, col, tol)).

8-connected flood-fill: every neighbour whose intensity differs from the seed value by ≤ tol is accepted. Coordinates are 1-based.

Parameters
IInput image.
rowSeed row (1-based).
colSeed column (1-based).
tolIntensity tolerance. Pass < 0 to request the auto-pick (32 for uint8 / int8, scaled by class range for other types).
mrMemory resource (nullptr → process default).
Returns
Logical mask of the connected region.

◆ graycoprops()

Value nk::image::graycoprops ( const Value & G,
std::pmr::memory_resource * mr = nullptr )

Texture statistics from a GLCM (S = graycoprops(G)).

Given a GLCM G (assumed normalised internally to a probability matrix p = G / sum(G)), returns a struct Value with the four canonical fields:

  • Contrast \( = \sum_{i,j} (i - j)^2\,p(i, j) \)
  • Correlation \( = \sum_{i,j} \frac{(i - \mu_i)(j - \mu_j)\,p(i, j)}{\sigma_i\,\sigma_j} \)
  • Energy \( = \sum_{i,j} p(i, j)^2 \)
  • Homogeneity \( = \sum_{i,j} \frac{p(i, j)}{1 + |i - j|} \)
Parameters
GGLCM (square matrix from graycomatrix).
mrMemory resource (nullptr → process default).
Returns
Struct Value with fields Contrast, Correlation, Energy, Homogeneity.
See also
graycomatrix

◆ graydiffweight()

Value nk::image::graydiffweight ( const Value & I,
double ref_gray_val,
double rolloff_factor,
double cutoff,
std::pmr::memory_resource * mr = nullptr )

Pixel weights from grayscale intensity difference (W = graydiffweight(I, refGrayVal [, NV...])).

Used by Fast-Marching-Method-based segmentation (imsegfmm). For each pixel: d = |I − refGrayVal|; linearly scale d to [1e-3, 1]; then W = 1 / (d^(1/RolloffFactor)). Pixels close to the reference get a very large weight (~10^6 with the default RolloffFactor = 0.5); far pixels get weight 1.

Reference value source. This typed entry-point takes a scalar refGrayVal; the engine adapter additionally exposes the four MATLAB R2025b signatures graydiffweight(I, refGrayVal), graydiffweight(I, MASK) — mean of I(MASK), graydiffweight(I, C, R) — mean at linear (R, C), graydiffweight(V, C, R, P) — 3-D version, each of which resolves to a single scalar reference internally.

Options:

  • RolloffFactor (default 0.5) — controls how fast W falls.
  • GrayDifferenceCutoff (default +Inf) — when finite, any pixel with d > cutoff (BEFORE scaling) is forced to 1 (largest scaled-d, smallest output weight).

Output class: single if I is single, else double (matches MATLAB R2025b).

Parameters
IGrayscale 2-D / 3-D image (any numeric class).
ref_gray_valReference intensity (scalar).
rolloff_factor> 0. Default 0.5.
cutoff>= 0 or +Inf (no cutoff). Default +Inf.
mrMemory resource (nullptr → process default).
Returns
Weight array (same shape as I).

◆ graydist()

Value nk::image::graydist ( const Value & I,
const Value & seeds,
const std::string & method,
std::pmr::memory_resource * mr = nullptr )

Gray-weighted geodesic distance transform (T = graydist(I, seeds [, method])).

Computes the minimum-cost path length from each pixel to the nearest seed, where the cost of stepping from pixel p to neighbour q is \( \text{cost}(p, q) = \chi(p, q) \cdot \frac{I(p) + I(q)}{2} \) with chamfer weight χ depending on method:

  • "chessboard" (default) — 8-conn, χ = 1 for all neighbours.
  • "cityblock" — 4-conn, χ = 1 (orth only).
  • "quasi-euclidean" — 8-conn, χ = 1 (orth), χ = √2 (diag).

Solved by Dijkstra over the pixel grid. Output is DOUBLE for DOUBLE input, SINGLE otherwise (matches MATLAB R2025b).

Reference: Soille, Morphological Image Analysis, 2nd ed., Springer, §4.4 (chamfer geodesic distance transform).

Parameters
I2-D grayscale image (any real numeric class).
seedsLinear seed indices (1-based, into column-major storage of I). Empty → all-Inf output.
method"chessboard" (default) / "cityblock" / "quasi-euclidean".
mrMemory resource (nullptr → process default).
Returns
Distance transform T, same shape as I.

◆ grayslice() [1/2]

Value nk::image::grayslice ( const Value & I,
int N,
std::pmr::memory_resource * mr = nullptr )

Multilevel thresholding into an indexed image, level-count form (L = grayslice(I, N)).

Equivalent to grayslice(I, [(1/N) … ((N-1)/N)]) scaled to the image's class range. Output is uint8 if N < 256, else double (1-based indexing).

Parameters
IInput image.
NNumber of output levels (≥ 1).
mrMemory resource (nullptr → process default).
Returns
Indexed image (uint8 or double).
See also
imquantize, multithresh

◆ grayslice() [2/2]

Value nk::image::grayslice ( const Value & I,
Span< const double > levels,
std::pmr::memory_resource * mr = nullptr )

Multilevel thresholding into an indexed image, explicit thresholds form (L = grayslice(I, [t1, t2, …])).

For floating-point images the threshold vector is clamped to [min(I), max(I)] (extending toward image bounds, never shrinking). Output is uint8 if levels.size() < 256, else double (1-based indexing).

Parameters
IInput image.
levelsExplicit threshold values (any length).
mrMemory resource (nullptr → process default).
Returns
Indexed image.
See also
imquantize, multithresh

◆ graythresh()

std::tuple< Value, Value > nk::image::graythresh ( const Value & I,
std::pmr::memory_resource * mr = nullptr )

Otsu's threshold and effectiveness metric ([level, em] = graythresh(I)).

Returns (threshold, em) both in [0, 1].

Parameters
IInput image.
mrMemory resource (nullptr → process default).
Returns
Tuple (level, em).
See also
otsuthresh, multithresh, imbinarize

◆ histeq()

Value nk::image::histeq ( const Value & I,
int n,
std::pmr::memory_resource * mr = nullptr )

Histogram equalisation (J = histeq(I, n)).

Equalises the image histogram across n bins (default 64).

Parameters
IInput image.
nNumber of histogram bins (default 64).
mrMemory resource (nullptr → process default).
Returns
Equalised image, same class as I.
See also
adapthisteq, imadjust

◆ hot_cmap()

Value nk::image::hot_cmap ( int n,
std::pmr::memory_resource * mr = nullptr )

Black-red-yellow-white colormap (map = hot(n)).

Piecewise R-then-G-then-B ramps with idx = floor(3/8 · n).

Parameters
nRow count.
mrMemory resource.
Returns
n × 3 colormap.

◆ hough()

void nk::image::hough ( const Value & BW,
double rho_res,
const Value & theta_deg,
Value & H_out,
Value & T_out,
Value & R_out,
std::pmr::memory_resource * mr = nullptr )

Standard Hough transform ([H, T, R] = hough(BW, ...)).

Computes the parameter-space accumulator for the line \( \rho = x \cos\theta + y \sin\theta \) over the foreground pixels of binary image BW. Each true pixel votes for every (θ, ρ) bin on its sinusoid; peaks in H represent collinear pixels.

Default θ grid is -90 : 1 : 89 degrees (180 bins). Default ρ grid is linspace(-D, D, 2·⌈D/rhoRes⌉+1) where D = √((M-1)² + (N-1)²). Custom theta (any vector in [-90, 90)) and rhoRes (positive scalar) override the defaults.

Reference: Gonzalez, Woods & Eddins, Digital Image Processing Using MATLAB, 2nd ed., Gatesmark, 2009.

Parameters
BW2-D binary mask (logical; numeric is cast).
rho_resBin spacing along ρ. Default 1.
theta_degTheta grid in degrees (any vector in [-90, 90)). Empty → default -90:1:89.
[out]H_outAccumulator (nRho × nTheta DOUBLE).
[out]T_outθ vector echoed (1 × nTheta).
[out]R_outρ vector (1 × nRho).
mrMemory resource (nullptr → process default).

◆ houghlines()

Value nk::image::houghlines ( const Value & BW,
const Value & theta_deg,
const Value & rho,
const Value & peaks,
double fillgap,
double minlength,
std::pmr::memory_resource * mr = nullptr )

Extract line segments from Hough-transform peaks (lines = houghlines(BW, theta, rho, peaks, ...)).

Walks each peak from houghpeaks, finds the nonzero pixels of BW that map to that bin, sorts them along the line direction, then splits the run into segments wherever consecutive pixels are farther than FillGap apart. Segments shorter than MinLength are discarded.

Returned struct-array fields per segment:

  • point1 — [x1, y1] endpoint (1-based image coords).
  • point2 — [x2, y2] endpoint.
  • theta — bin angle in degrees.
  • rho — bin distance.

Reference: Gonzalez/Woods/Eddins, Digital Image Processing Using MATLAB, Prentice Hall 2003.

Parameters
BW2-D binary image (logical or numeric).
theta_degθ vector from hough.
rhoρ vector from hough.
peaksP × 2 index matrix from houghpeaks.
fillgapMerge consecutive sub-segments within this pixel distance. Default 20.
minlengthDiscard segments shorter than this. Default 40.
mrMemory resource (nullptr → process default).
Returns
1 × N struct array (possibly empty) with the four fields above.

◆ houghpeaks()

Value nk::image::houghpeaks ( const Value & H,
std::size_t numpeaks,
double threshold,
std::size_t nhoodRho,
std::size_t nhoodTheta,
const Value & theta_deg,
std::pmr::memory_resource * mr = nullptr )

Find peaks in a Hough-transform accumulator (P = houghpeaks(H, NumPeaks, ...)).

Iteratively picks the global maximum of H, records its [rho_idx, theta_idx], then zeroes out a rectangular neighbourhood of size NHoodSize around it. Stops when either NumPeaks peaks are found or the current max falls below threshold (default 0.5·max(H(:))).

When theta covers a full antisymmetric range [-90, 90), the neighbourhood suppression wraps across the θ edge with rho flip (so a peak near θ = ±90° also suppresses the equivalent peak on the opposite side).

NHoodSize default: smallest odd integers ≥ size(H) / 50, minimum [1 1].

Parameters
HnRho × nTheta Hough accumulator from hough.
numpeaksMax number of peaks to return.
thresholdMinimum accumulator value (negative → use default 0.5·max(H(:))).
nhoodRhoSuppression neighbourhood rows (odd). Pass 0 → use default.
nhoodThetaSuppression neighbourhood cols (odd). Pass 0 → use default.
theta_degTheta vector used by hough (empty → -90:1:89, suppression wraps over [-90, 90)).
mrMemory resource (nullptr → process default).
Returns
P × 2 DOUBLE matrix; each row [rho_idx, theta_idx] is 1-based into H.

◆ hsv2rgb()

Value nk::image::hsv2rgb ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

HSV → RGB (inverse of rgb2hsv).

Parameters
xHSV image / colormap.
mrMemory resource (nullptr → process default).
Returns
RGB image / colormap (DOUBLE).

◆ hsv_cmap()

Value nk::image::hsv_cmap ( int n,
std::pmr::memory_resource * mr = nullptr )

Hue-rotation colormap (map = hsv(n)).

Equivalent to hsv2rgb([(0:n-1)'/n, 1, 1]).

Parameters
nRow count.
mrMemory resource.
Returns
n × 3 colormap.

◆ idct2()

Value nk::image::idct2 ( const Value & B,
std::pmr::memory_resource * mr = nullptr )

Inverse 2-D DCT (A = idct2(B)).

Exact left-inverse of dct2.

Parameters
B2-D DCT coefficients.
mrMemory resource (nullptr → process default).
Returns
Reconstructed M × N matrix.
See also
dct2

◆ illumgray()

Value nk::image::illumgray ( const Value & A,
const std::vector< double > & P,
const Value & mask,
std::pmr::memory_resource * mr = nullptr )

Grey-World illuminant estimate (illum = illumgray(A [, P] [, 'Mask', M])).

Returns a 1×3 RGB row-vector approximating the scene illuminant.

Algorithm. Sorts the masked pixels by L2 norm of (R, G, B), optionally trims the bottom p_lo% and top p_hi%, then returns the per-channel mean of the survivors (Grey-World hypothesis, Buchsbaum 1980). P is either a scalar (applied to both ends) or a 2-element vector [p_lo, p_hi], each in [0, 50). MATLAB default P = 0 (no trimming).

Parameters
AH × W × 3 numeric image.
PPercentile(s); empty vector → P=0.
maskOptional H × W mask; empty → all.
mrMemory resource (nullptr → process default).
Returns
1 × 3 DOUBLE illuminant.

◆ illumpca()

Value nk::image::illumpca ( const Value & A,
double P,
const Value & mask,
std::pmr::memory_resource * mr = nullptr )

PCA-based illuminant estimate (illum = illumpca(A [, P] [, 'Mask', M])).

Returns a 1×3 RGB row-vector approximating the scene illuminant using the dominant direction of the darkest and brightest P% of pixels (Cheng-Prasad-Brown, JOSA A 31(5), 2014, p. 1049-1058).

Algorithm. Pixels are ordered by the magnitude of their projection on the mean colour direction. The top-P% brightest and bottom-P% darkest pixels (default P = 3.5) are kept; PCA (SVD of the not-mean-centred 3-column matrix) gives the principal direction, which is returned as abs(V(:,1)) so the illuminant always lives in the first octant.

Degenerate case (single colour, V == I, or near-equal singular values): the mean of the selected colours is returned instead, matching MATLAB's source.

Parameters
AH × W × 3 numeric image.
PPercentile in (0, 50]. Default 3.5. P >= 50 uses all pixels.
maskOptional H × W mask; empty → all.
mrMemory resource (nullptr → process default).
Returns
1 × 3 DOUBLE illuminant.

◆ illumwhite()

Value nk::image::illumwhite ( const Value & A,
double P,
const Value & mask,
std::pmr::memory_resource * mr = nullptr )

White-Patch illuminant estimate (illum = illumwhite(A [, P] [, 'Mask', M])).

Returns a 1×3 RGB row-vector approximating the scene illuminant.

Algorithm. With P == 0, returns per-channel max over masked pixels (classical White-Patch retinex, Land & McCann 1971). With P > 0, returns the per-channel mean of the top-P% pixels by L2 norm of (R, G, B) (top-percentile variant, Banić & Lončarić 2014). MATLAB default P = 1.

Parameters
AH × W × 3 numeric image.
PPercentile in [0, 100). Default 1 (top 1 %).
maskOptional H × W logical/numeric mask; empty → use all.
mrMemory resource (nullptr → process default).
Returns
1 × 3 DOUBLE illuminant.

◆ im2col()

Value nk::image::im2col ( const Value & A,
int m,
int n,
const std::string & block_type,
std::pmr::memory_resource * mr = nullptr )

Rearrange image neighbourhoods into matrix columns (B = im2col(A, [m n], block_type)).

  • "sliding" (default): every m×n window of A becomes a column. Output is m·n × (M-m+1)·(N-n+1).
  • "distinct": non-overlapping tiles, zero-padded when A's dims aren't multiples of m or n.

Output class matches A.

Parameters
AInput image.
mWindow row count.
nWindow column count.
block_type"sliding" (default) or "distinct".
mrMemory resource (nullptr → process default).
Returns
Column-stacked neighbourhood matrix.
See also
col2im

◆ im2double()

Value nk::image::im2double ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

Convert to DOUBLE in [0, 1] (B = im2double(A)).

Integer inputs are scaled by their class range. Float inputs are cast to DOUBLE without rescaling.

Parameters
xInput image.
mrMemory resource (nullptr → process default).
Returns
DOUBLE image in [0, 1].
See also
im2single, im2uint8, im2uint16, im2int16, mat2gray

◆ im2gray()

Value nk::image::im2gray ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

RGB → grayscale dispatcher (Y = im2gray(X)).

If X has 3 pages, applies rgb2gray; otherwise returns X unchanged (already grayscale).

Parameters
xInput image.
mrMemory resource (nullptr → process default).
Returns
Grayscale image.
See also
rgb2gray

◆ im2int16()

Value nk::image::im2int16 ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

Convert to INT16 (B = im2int16(A)).

Parameters
xInput image.
mrMemory resource (nullptr → process default).
Returns
INT16 image.
See also
im2uint16, im2double

◆ im2single()

Value nk::image::im2single ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

Convert to SINGLE in [0, 1] (B = im2single(A)).

Same scaling rules as im2double.

Parameters
xInput image.
mrMemory resource (nullptr → process default).
Returns
SINGLE image in [0, 1].
See also
im2double

◆ im2uint16()

Value nk::image::im2uint16 ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

Convert to UINT16 (B = im2uint16(A)).

Parameters
xInput image.
mrMemory resource (nullptr → process default).
Returns
UINT16 image.
See also
im2uint8, im2double

◆ im2uint8()

Value nk::image::im2uint8 ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

Convert to UINT8 (B = im2uint8(A)).

See file note for scaling rules.

Parameters
xInput image.
mrMemory resource (nullptr → process default).
Returns
UINT8 image.
See also
im2uint16, im2double

◆ imabsdiff()

Value nk::image::imabsdiff ( const Value & x,
const Value & y,
std::pmr::memory_resource * mr = nullptr )

Saturating absolute difference (Z = imabsdiff(X, Y)).

Computes Z = |X − Y| with saturation.

Parameters
xFirst image.
ySecond image.
mrMemory resource (nullptr → process default).
Returns
Image of the same class and shape as X.
See also
imsubtract

◆ imadd()

Value nk::image::imadd ( const Value & x,
const Value & y,
std::pmr::memory_resource * mr = nullptr )

Saturating image addition (Z = imadd(X, Y)).

Element-wise \( Z = X + Y \) with saturation for integer outputs (uint8 → clamp to [0, 255], uint16 → [0, 65535], int16 → [-32768, 32767]). Floating-point inputs pass through without clipping.

Either operand may be a scalar (broadcasts). Output class equals X's class; Y is cast on the fly if needed.

Parameters
xFirst image (or scalar).
ySecond image (or scalar).
mrMemory resource (nullptr → process default).
Returns
Image of the same class and shape as X.
See also
imsubtract, immultiply, imdivide

◆ imadjust()

Value nk::image::imadjust ( const Value & I,
double low_in,
double high_in,
double low_out,
double high_out,
double gamma,
std::pmr::memory_resource * mr = nullptr )

Affine intensity remap with optional gamma (J = imadjust(...)).

Implements imadjust(I, [low_in high_in], [low_out high_out], gamma). Pass NaN for low_in / high_in to trigger an automatic stretchlim default; pass NaN for the output limits to map to [0, 1].

Parameters
IInput image.
low_inLow input intensity (NaN → auto via stretchlim).
high_inHigh input intensity (NaN → auto via stretchlim).
low_outLow output intensity (NaN → 0).
high_outHigh output intensity (NaN → 1).
gammaGamma exponent (1.0 = linear, > 1 darkens).
mrMemory resource (nullptr → process default).
Returns
Remapped image of the same class as I.
See also
histeq, adapthisteq

◆ imapplymatrix()

Value nk::image::imapplymatrix ( const Value & M,
const Value & x,
ValueType output_class,
std::pmr::memory_resource * mr = nullptr )

Apply a colour-space transform matrix (Y = imapplymatrix(M, X)).

For an H×W×N image X and an M×N matrix M, computes the per-pixel matrix-vector product along the third axis: Y(:,:,i) = sum_j M(i,j) · X(:,:,j). Typical use is a 3×3 RGB-to-YCbCr / sRGB-to-XYZ transform.

Parameters
MM×N transform matrix.
xH×W×N input image.
output_classTarget class (defaults to X's float type).
mrMemory resource (nullptr → process default).
Returns
H×W×M transformed image.
Exceptions
Errorif M cols ≠ X pages.

◆ imbilatfilt()

Value nk::image::imbilatfilt ( const Value & I,
double degreeOfSmoothing,
double spatialSigma,
std::pmr::memory_resource * mr = nullptr )

Edge-preserving bilateral filter (B = imbilatfilt(I, degreeOfSmoothing, spatialSigma)).

Weights combine a spatial Gaussian (σ = spatialSigma) and a range Gaussian over intensity difference (variance = degreeOfSmoothing). Replicate boundary.

Parameters
IInput image.
degreeOfSmoothingIntensity-range variance.
spatialSigmaSpatial-Gaussian σ in pixels.
mrMemory resource (nullptr → process default).
Returns
Filtered image, same class as I.

◆ imbinarize() [1/2]

Value nk::image::imbinarize ( const Value & I,
const Value & T,
std::pmr::memory_resource * mr = nullptr )

Per-pixel threshold (BW = imbinarize(I, T)).

T must have the same numel as I. Composes naturally with adaptthresh.

Parameters
IInput image.
TPer-pixel threshold matrix.
mrMemory resource (nullptr → process default).
Returns
LOGICAL mask, same shape as I.
See also
adaptthresh

◆ imbinarize() [2/2]

Value nk::image::imbinarize ( const Value & I,
double thresh,
std::pmr::memory_resource * mr = nullptr )

Threshold an image (BW = imbinarize(I, thresh)).

Scalar-threshold overload. Pass NaN for thresh to auto-pick via graythresh.

Parameters
IInput image.
threshScalar threshold (NaN → auto via graythresh).
mrMemory resource (nullptr → process default).
Returns
LOGICAL mask, same shape as I.
See also
graythresh, adaptthresh

◆ imbothat()

Value nk::image::imbothat ( const Value & I,
const Value & SE,
std::pmr::memory_resource * mr = nullptr )

Black top-hat (J = imbothat(I, SE) = imclose(I, SE) - I).

Highlights dark structures smaller than SE on a bright background.

Parameters
IInput image.
SEStructuring element.
mrMemory resource (nullptr → process default).
Returns
Bottom-hat image.
See also
imtophat, imclose

◆ imboxfilt()

Value nk::image::imboxfilt ( const Value & I,
int filter_size,
std::pmr::memory_resource * mr = nullptr )

2-D box / mean filter (B = imboxfilt(I, filter_size)).

Replicate boundary. Constant-time per-pixel via integral images.

Parameters
IInput image.
filter_sizeSquare neighbourhood side length (odd).
mrMemory resource (nullptr → process default).
Returns
Filtered image, same class as I.
See also
imgaussfilt, imboxfilt3

◆ imboxfilt3()

Value nk::image::imboxfilt3 ( const Value & V,
int fH,
int fW,
int fP,
std::pmr::memory_resource * mr = nullptr )

3-D box (mean) filter (J = imboxfilt3(V, fH, fW, fP)).

Per-axis filter sizes default to 3. Replicate boundary on all 3 axes. Output type matches input.

Parameters
VInput volume (3-D).
fHFilter height (rows).
fWFilter width (cols).
fPFilter depth (pages).
mrMemory resource (nullptr → process default).
Returns
Filtered volume, same class as V.
See also
imboxfilt, imgaussfilt3

◆ imcast()

Value nk::image::imcast ( const Value & I,
const std::string & type,
std::pmr::memory_resource * mr = nullptr )

Generic class converter (B = imcast(I, type)).

Dispatches to the appropriate im2* helper based on the target class name. LOGICAL target maps non-zero entries to 1; casting from LOGICAL to integer maps true → intmax of the target. The "indexed" third-arg mode is not yet supported.

Parameters
IInput image.
typeTarget class: "double", "single", "uint8", "uint16", "int16", "logical".
mrMemory resource (nullptr → process default).
Returns
Image cast to type.
Exceptions
ErrorUnknown / unsupported type name.

◆ imclearborder()

Value nk::image::imclearborder ( const Value & BW,
int conn,
std::pmr::memory_resource * mr = nullptr )

Remove border-touching components (J = imclearborder(BW, conn)).

marker = BW restricted to the rim, R = imreconstruct(marker, BW, conn), J = BW & ~R.

Parameters
BWBinary input.
connConnectivity.
mrMemory resource (nullptr → process default).
Returns
Binary image with rim components removed.
See also
imkeepborder

◆ imclose()

Value nk::image::imclose ( const Value & I,
const Value & SE,
std::pmr::memory_resource * mr = nullptr )

Morphological closing (J = imclose(I, SE) = imerode(imdilate(I, SE), SE)).

Parameters
IInput image.
SEStructuring element.
mrMemory resource (nullptr → process default).
Returns
Closed image.
See also
imopen

◆ imcolordiff()

Value nk::image::imcolordiff ( const Value & I1,
const Value & I2,
const std::string & standard,
bool is_input_lab,
double kL,
double kC,
double kH,
double K1,
double K2,
std::pmr::memory_resource * mr = nullptr )

CIE94 / CIEDE2000 colour difference (dE = imcolordiff(I1, I2, ...)).

Default standard = CIE94. Pass standard = "CIEDE2000" to use the 2000 revision. Inputs may be:

  • c × 3 colour lists (c × 1 output);
  • H × W × 3 images (H × W output);
  • higher-dim arrays where the 3rd dim is the colour channel (output preserves all other dims, dropping the channel axis).

Weighting factors (textile / graphic-arts defaults):

  • kL, kC, kH — parametric factors for L*, C*, H* (default 1).
  • K1, K2 — CIE94 chroma / hue weighting constants (defaults 0.045 and 0.015 — the graphic-arts setting). For textile applications use K1 = 0.048, K2 = 0.014.

is_input_lab = false (default) → inputs are RGB and are converted to L*a*b* with rgb2lab. true → inputs are already Lab and the conversion is skipped (only DOUBLE / SINGLE inputs allowed in that case).

Reference: ISO 11664-6:2014 (CIE2000) and CIE Publ. 116-1995 (CIE94). MATLAB R2025b images.color.internal.deltaE94 / deltaE2000 — verified bit-equal on probe outputs.

Parameters
I1First colour image / list.
I2Second colour image / list (same shape).
standard"CIE94" or "CIEDE2000".
is_input_labSkip the RGB→Lab step.
kLL* weighting factor (must be > 0).
kCC* weighting factor (must be > 0).
kHH* weighting factor (must be > 0).
K1CIE94 chroma constant.
K2CIE94 hue constant.
mrMemory resource (nullptr → process default).
Returns
Per-pixel colour difference (channel dim removed).

◆ imcomplement()

Value nk::image::imcomplement ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

Image complement (Y = imcomplement(X)).

  • integer classes: Y = MAX(class) - X (uint8 → 255 − X, etc.).
  • floating point: Y = 1 - X (assumes input in [0, 1]).
  • logical: Y = ~X (bitwise complement).
Parameters
xInput image.
mrMemory resource (nullptr → process default).
Returns
Complemented image of the same class.

◆ imcrop()

Value nk::image::imcrop ( const Value & A,
double xmin,
double ymin,
double width,
double height,
std::pmr::memory_resource * mr = nullptr )

Crop a rectangular region (B = imcrop(A, [xmin ymin width height])).

Coordinates are 1-based. Sub-pixel coordinates are rounded; out-of-bounds requests are clamped to the image extent.

Parameters
AInput image.
xminTop-left column (1-based).
yminTop-left row (1-based).
widthRectangle width (columns).
heightRectangle height (rows).
mrMemory resource (nullptr → process default).
Returns
Cropped sub-image.
See also
imresize

◆ imcrop3()

Value nk::image::imcrop3 ( const Value & V,
const Value & cuboid,
std::pmr::memory_resource * mr = nullptr )

Crop a 3-D image volume (VOUT = imcrop3(V, cuboid)).

cuboid = [XMIN YMIN ZMIN WIDTH HEIGHT DEPTH]. The crop volume covers columns round(XMIN) .. round(XMIN+WIDTH), rows round(YMIN) .. round(YMIN+HEIGHT), and pages round(ZMIN) .. round(ZMIN+DEPTH) — i.e. an inclusive (width+1) × (height+1) × (depth+1) block in MATLAB's spatial (X, Y, Z) = (col, row, page) convention.

Class is preserved. Multi-channel 3-D / 4-D volumes are supported: the 4th dimension passes through unchanged. Out-of-bounds cuboid throws.

Parameters
V3-D / 4-D numeric, logical, or integer volume.
cuboid6-element [XMIN YMIN ZMIN W H D] vector.
mrMemory resource (nullptr → process default).
Returns
Cropped sub-volume.

◆ imdiffusefilt()

Value nk::image::imdiffusefilt ( const Value & I,
const Value & thresh,
std::size_t N,
const std::string & connectivity,
const std::string & conduction,
std::pmr::memory_resource * mr = nullptr )

Anisotropic-diffusion edge-preserving smoothing (B = imdiffusefilt(I, ...)).

Perona-Malik nonlinear diffusion (1990): each iteration, compute nearest-neighbour intensity diffs, weight them by a contrast-sensitive conduction coefficient, then update I += rate · sum(flux).

Conductance: exponential: c(∇) = exp(-(|∇|/K)²) quadratic: c(∇) = 1 / (1 + (|∇|/K)²)

connectivity = "maximal" (default) uses 8 neighbour directions; "minimal" uses 4. Default K = 0.1 · diff( getrangefromclass(I)) (0.1 for double, 25.5 for uint8, etc.). Default iterations N = 5 when gradientThreshold is scalar; when it's a vector, N = numel(gradientThreshold) and each iteration uses its own K.

2-D inputs only (3-D / volume diffusion deferred — MATLAB's diffusefilt3D adds 27-point stencils which roughly triples the code).

References: [1] P. Perona & J. Malik, "Scale-Space and Edge Detection Using Anisotropic Diffusion", IEEE TPAMI 12(7), 1990. [2] G. Gerig et al., "Nonlinear anisotropic filtering of MRI data", IEEE Trans. Medical Imaging 11(2), 1992.

Computation uses double precision for double input and single for everything else (matching MATLAB). Output class equals input class.

Parameters
I2-D image (any real numeric class).
threshGradientThreshold (scalar or length-N vector); negative → use class default.
NNumberOfIterations (0 → derive from thresh: 5 if scalar, length if vector).
connectivity"maximal" (default) or "minimal".
conduction"exponential" (default) or "quadratic".
mrMemory resource (nullptr → process default).
Returns
Smoothed image, same shape and class as I.

◆ imdilate()

Value nk::image::imdilate ( const Value & I,
const Value & SE,
std::pmr::memory_resource * mr = nullptr )

Grayscale dilation (J = imdilate(I, SE)).

Each output pixel is the maximum of I over the SE-marked neighbourhood.

Parameters
IInput image.
SEStructuring element.
mrMemory resource (nullptr → process default).
Returns
Dilated image.
See also
imerode, imclose

◆ imdivide()

Value nk::image::imdivide ( const Value & x,
const Value & y,
std::pmr::memory_resource * mr = nullptr )

Saturating element-wise division (Z = imdivide(X, Y)).

Division by zero in integer classes saturates to the output type's max value; in floats it produces Inf/NaN per IEEE-754.

Parameters
xNumerator image (or scalar).
yDenominator image (or scalar).
mrMemory resource (nullptr → process default).
Returns
Image of the same class and shape as X.
See also
imadd, immultiply

◆ imerode()

Value nk::image::imerode ( const Value & I,
const Value & SE,
std::pmr::memory_resource * mr = nullptr )

Grayscale erosion (J = imerode(I, SE)).

Each output pixel is the minimum of I over the SE-marked neighbourhood. For LOGICAL input: pixel = 1 iff every SE-marked neighbour is 1.

Parameters
IInput image.
SEStructuring element.
mrMemory resource (nullptr → process default).
Returns
Eroded image, same shape as I.
See also
imdilate, imopen, strel

◆ imextendedmax()

Value nk::image::imextendedmax ( const Value & I,
double h,
int conn,
std::pmr::memory_resource * mr = nullptr )

Extended-maxima transform (J = imextendedmax(I, h, conn)).

LOGICAL mask of regional maxima of imhmax: keeps only peaks with height >= h above their surroundings.

Parameters
IInput image.
hHeight threshold.
connConnectivity.
mrMemory resource (nullptr → process default).
Returns
LOGICAL extended-maxima mask.
See also
imhmax, imextendedmin

◆ imextendedmin()

Value nk::image::imextendedmin ( const Value & I,
double h,
int conn,
std::pmr::memory_resource * mr = nullptr )

Extended-minima transform (J = imextendedmin(I, h, conn)).

Dual of imextendedmax: troughs with depth >= h.

Parameters
IInput image.
hDepth threshold.
connConnectivity.
mrMemory resource (nullptr → process default).
Returns
LOGICAL extended-minima mask.
See also
imextendedmax

◆ imfill_holes()

Value nk::image::imfill_holes ( const Value & BW,
int conn,
std::pmr::memory_resource * mr = nullptr )

Fill holes in a binary image (J = imfill(BW, 'holes', conn)).

Holes are 0-pixels NOT connectivity-reachable from the image border. Implementation: reconstruct ~BW from its border seed, then invert.

Parameters
BWBinary image.
connConnectivity (4 or 8).
mrMemory resource (nullptr → process default).
Returns
Hole-filled binary image.
See also
imreconstruct

◆ imfilter()

Value nk::image::imfilter ( const Value & I,
const Value & h,
PadMode boundary,
double pad_value,
bool full,
bool flip_kernel,
std::pmr::memory_resource * mr = nullptr )

2-D linear filtering (B = imfilter(I, h, ...)).

Direct convolution or correlation of I with kernel h.

Parameters
IInput image.
hFilter kernel (any size).
boundaryPadMode (Constant → use pad_value).
pad_valueConstant pad value.
fullfalse → output size = input ("same"); true → output size = input + kernel − 1 ("full").
flip_kerneltrue → convolution (kernel flipped); false → correlation.
mrMemory resource (nullptr → process default).
Returns
Filtered image, same class as I.

◆ imfinfo()

Value nk::image::imfinfo ( const std::string & path,
std::pmr::memory_resource * mr = nullptr )

Read image header metadata without decoding pixels (S = imfinfo(path)).

Returns a struct with the fields:

  • Filename — path passed in.
  • Format — "png"|"jpg"|"bmp"|"gif"|"pnm"|"hdr"|"psd"|"tga".
  • Width, Height — image dimensions in pixels.
  • NumberOfChannels — 1, 3, or 4.
  • NumberOfSamples — 1, 3, or 4 (MATLAB standard alias for channels).
  • ColorType — "grayscale"|"truecolor"|"truecoloralpha".
  • FileSize — bytes on disk.
Parameters
pathFilesystem path.
mrMemory resource (nullptr → process default).
Returns
Struct Value with the metadata fields above.
See also
imread

◆ imfinfoFromBytes()

Value nk::image::imfinfoFromBytes ( const std::string & bytes,
const std::string & filename,
std::pmr::memory_resource * mr = nullptr )

imfinfo from already-loaded bytes (the engine entry feeds these from the VFS so it works on the virtual + real filesystem).

filename is recorded in the returned struct's Filename field but is not opened.

See also
imfinfo

◆ imflatfield()

Value nk::image::imflatfield ( const Value & I,
double sigma,
const Value & mask,
std::pmr::memory_resource * mr = nullptr )

Flat-field correction (J = imflatfield(I, sigma, mask)).

Divides the image by a low-pass estimate of its background and rescales so the mean is preserved: F = imgaussfilt(I_double, sigma), J = I_double ./ F .* mean(F[mask]). Output is cast back to the input class with saturation. The optional mask restricts the mean-of-F average.

Parameters
IInput image.
sigmaGaussian σ (px) for the background estimate.
maskOptional logical mask (pass Value::Empty to skip).
mrMemory resource (nullptr → process default).
Returns
Corrected image, same class as I.

◆ imfuse()

Value nk::image::imfuse ( const Value & A,
const Value & B,
const std::string & method,
const std::string & scaling,
const Value & channels,
std::pmr::memory_resource * mr = nullptr )

Composite two images for visual comparison (C = imfuse(A, B, method, ...)).

Builds a UINT8 composite of A and B for visual comparison (e.g. registration QA). Five fusion methods (default "falsecolor"):

  • "falsecolor" — convert each input to grayscale, scale, then assign to RGB channels per ColorChannels (default "green-magenta" = [2 1 2]).
  • "blend" — alpha-blend at 50/50 in overlap; pass- through outside overlap (no spatial-ref form here, so the overlap is the whole image).
  • "diff" — |A - B| as scaled grayscale.
  • "checkerboard" — alternating 8x8 super-blocks from A/B (block tile resized to image size by nearest neighbour).
  • "montage" — [A B] side-by-side concatenation.

Scaling controls grayscale conversion:

  • "independent" (default) — scale each input to [0, 1] before im2uint8.
  • "joint" — concatenate, scale together, then split.
  • "none" — no rescale (just class cast).

ColorChannels for "falsecolor" only: 3-element vector [R G B] with values in {0, 1, 2} (image index, 0 = neither) or the named shortcuts "red-cyan" = [1 2 2], or "green-magenta" = [2 1 2] (default).

If A and B differ in H × W, both are zero-padded to the element-wise max along each dimension before fusion.

Spatial referencing (the (A, RA, B, RB) form using imref2d) is not supported — imref2d is a MATLAB OOP class and §0 of the library policy forbids us from implementing it. The two- output form [C, RC] is therefore not exposed.

Output is always UINT8 with class(C) = uint8.

Parameters
AFirst image (grayscale 2-D, RGB 2-D x 3, or logical).
BSecond image (any numeric class).
method"falsecolor" (def) / "blend" / "diff" / "checkerboard" / "montage".
scaling"independent" (def) / "joint" / "none".
channels3-element vector in {0,1,2} for "falsecolor" (default [2 1 2] = green-magenta).
mrMemory resource (nullptr → process default).
Returns
UINT8 composite image.

◆ imgaborfilt()

void nk::image::imgaborfilt ( const Value & A,
double wavelength,
double orientation,
double sfb,
double aspect,
Value & mag_out,
Value & phase_out,
std::pmr::memory_resource * mr = nullptr )

Apply a single Gabor filter to a 2-D image ([mag, phase] = imgaborfilt(A, wavelength, orientation, ...)).

Single-filter form (the gabor MATLAB-OOP bank object is out of scope per §0; multiple wavelengths/orientations require calling this function in a loop).

Frequency-domain implementation matching MATLAB R2025b's images.internal.gaborFilterFFT:

SigmaX = wavelength / π · √(log 2 / 2) · (2^B + 1) / (2^B − 1) SigmaY = SigmaX / aspect r = max(⌈7·SigmaX⌉, ⌈7·SigmaY⌉) Pad A by r replicate, FFT-2D, multiply by ifftshift(H), IFFT-2D, crop back to size(A).

H(u, v) = 2π·SigmaX·SigmaY · exp(−½ ((u'−1/λ)²/σ_u² + v'²/σ_v²)) u', v' rotated by orientation, σ_u = 1/(2π·SigmaX), σ_v = 1/(2π·SigmaY), u, v on a normalised frequency grid.

References: [1] Jain & Farrokhnia, "Unsupervised Texture Segmentation Using Gabor Filters", 1991. [2] Kruizinga & Petkov, "Nonlinear Operator in Oriented Texture", IEEE Trans. Image Processing 1999.

Output class equals input class (double or single).

Parameters
A2-D image (real, finite).
wavelengthSinusoid wavelength (pixels/cycle), ≥ 2.
orientationFilter orientation in degrees.
sfbSpatialFrequencyBandwidth (default 1).
aspectSpatialAspectRatio (default 0.5).
[out]mag_outMagnitude response.
[out]phase_outPhase response (radians).
mrMemory resource (nullptr → process default).

◆ imgaussfilt()

Value nk::image::imgaussfilt ( const Value & I,
double sigma,
int filter_size,
std::pmr::memory_resource * mr = nullptr )

2-D Gaussian filter (B = imgaussfilt(I, sigma, filter_size)).

Boundary handling: replicate; output size = input.

Parameters
IInput image.
sigmaStandard deviation in pixels.
filter_sizeFilter side length (0 → default 2·ceil(2σ)+1).
mrMemory resource (nullptr → process default).
Returns
Filtered image, same class as I.
See also
imgaussfilt3, imboxfilt

◆ imgaussfilt3()

Value nk::image::imgaussfilt3 ( const Value & V,
double sigH,
double sigW,
double sigP,
std::pmr::memory_resource * mr = nullptr )

3-D Gaussian filter (J = imgaussfilt3(V, sigH, sigW, sigP)).

Separable 1-D convolutions along each axis with replicate boundary. Per-axis filter sizes default to 2·ceil(2σ)+1. Output type matches input.

Parameters
VInput volume (3-D).
sigHσ along rows (pixels).
sigWσ along cols (pixels).
sigPσ along pages (pixels).
mrMemory resource (nullptr → process default).
Returns
Filtered volume, same class as V.
See also
imgaussfilt

◆ imgradient()

std::tuple< Value, Value > nk::image::imgradient ( const Value & I,
const std::string & method,
std::pmr::memory_resource * mr = nullptr )

Gradient magnitude and direction ([Gmag, Gdir] = imgradient(I, method)).

Equivalent to running imgradientxy and converting to polar: \( G_\text{mag} = \sqrt{G_x^2 + G_y^2} \), \( G_\text{dir} = \text{atan2}(-G_y, G_x) \) in degrees (−180 ≤ Gdir ≤ 180; the -Gy flip makes the angle increase counter-clockwise in screen coordinates).

See also
imgradientxy, edge

◆ imgradient3()

std::tuple< Value, Value, Value > nk::image::imgradient3 ( const Value & V,
const std::string & method,
std::pmr::memory_resource * mr = nullptr )

3-D gradient magnitude + spherical direction ([Gmag, Gaz, Gelev] = imgradient3(V, method) or (Gx, Gy, Gz) inputs).

Gmag = hypot(hypot(Gx, Gy), Gz), Gaz = atan2(-Gy, Gx) (degrees), Gelev = atan2(Gz, hypot(Gx, Gy)) (degrees).

Single-output form returns only Gmag. The (Gx, Gy, Gz) alternate form skips the convolution step (used when the caller already has the directional gradients).

See also
imgradientxyz

◆ imgradientxy()

std::tuple< Value, Value > nk::image::imgradientxy ( const Value & I,
const std::string & method,
std::pmr::memory_resource * mr = nullptr )

Component gradients ([Gx, Gy] = imgradientxy(I, method)).

Computes the horizontal and vertical first-order partial derivatives of I using one of:

method kernel
"sobel" (def.) 3×3 Sobel operator
"prewitt" 3×3 Prewitt
"central" central difference: [1 0 -1] / 2
"intermediate" forward difference: [1 -1]

Outputs are DOUBLE images of the same H×W as I.

Parameters
IInput image (any numeric class; cast to double).
methodGradient kernel name (case-sensitive).
mrMemory resource (nullptr → process default).
Returns
(Gx, Gy).
See also
imgradient, edge

◆ imgradientxyz()

std::tuple< Value, Value, Value > nk::image::imgradientxyz ( const Value & V,
const std::string & method,
std::pmr::memory_resource * mr = nullptr )

3-D component gradients ([Gx, Gy, Gz] = imgradientxyz(V, method)).

Supports "sobel" (default), "prewitt", "central", and "intermediate". The Sobel / Prewitt kernels are the standard 3×3×3 separable extensions used by MATLAB R2025b (Sobel weights [1, 3, 3, 1]-style — not the naive [1, 2, 1] 2-D extension). "central" ≡ gradient(V); "intermediate" ≡ forward diff with the trailing slice zero-padded.

Replicate boundary handling for the convolution kernels. Output class is single if V is single, else double.

Parameters
V3-D grayscale volume.
method"sobel" / "prewitt" / "central" / "intermediate".
mrMemory resource (nullptr → process default).
Returns
Tuple (Gx, Gy, Gz) (same shape as V).

◆ imguidedfilter()

Value nk::image::imguidedfilter ( const Value & A,
const Value & G,
int nhood,
double eps,
std::pmr::memory_resource * mr = nullptr )

Edge-preserving guided filter (B = imguidedfilter(A, G, ...)).

Smooths image A using G as a guidance image (often A itself for edge-preserving denoising). Outputs a value whose local linear regression on G (within a neighborhood) best reconstructs A:

meanI = box(G) meanP = box(A) corrI = box(G·G) corrIP = box(G·A) varI = corrI − meanI² covIP = corrIP − meanI·meanP a = covIP / (varI + ε) b = meanP − a·meanI B = box(a)·G + box(b)

Reference: K. He, J. Sun, X. Tang, "Guided Image Filtering", IEEE TPAMI 35(6), 1397-1409, 2013.

Grayscale guide only here. RGB-guide (color-covariance 3×3 inversion via Cramer's rule) and the Fast-Guided-Filter downsample variant are deferred.

Default nhood = 5 (square 5×5). Default eps = 0.01 · diff( getrangefromclass(A))² (e.g. 0.01 for double, 650.25 for uint8).

Output class equals input class of A.

Parameters
AImage to filter (2-D; multi-channel uses same G per channel).
GGuidance image (Value::Empty → reuse A). Same H×W as A.
nhoodNeighborhood side length (positive odd; default 5).
epsSmoothing degree (negative → use class-based default).
mrMemory resource (nullptr → process default).
Returns
Filtered image, same shape and class as A.

◆ imhist()

std::tuple< Value, Value > nk::image::imhist ( const Value & I,
int n,
std::pmr::memory_resource * mr = nullptr )

Image histogram ([counts, bin_centers] = imhist(I, n)).

Default n depends on input class: 256 for uint8, 65536 for uint16, 64 for double in [0, 1].

Parameters
IInput image (any numeric class).
nBin count.
mrMemory resource (nullptr → process default).
Returns
(counts, centers).

◆ imhistmatch()

Value nk::image::imhistmatch ( const Value & I,
const Value & ref,
int nbins,
Value * hgramOut = nullptr,
std::pmr::memory_resource * mr = nullptr )

Histogram matching to a reference image ([J, hgram] = imhistmatch(I, ref, nbins)).

Adjusts I's histogram to match ref's via CDF matching (single-channel), following MATLAB R2025b: nbins defaults to 64 for every class; both histograms use MATLAB's imhist centred binning (round(u·(nbins−1))); each input bin maps to the output grey level (j−1)/(nbins−1) where j is the smallest reference bin with cdfR(j) ≥ cdfI(i). Output class matches I.

Parameters
ISource image.
refReference image (its histogram is the target).
nbinsHistogram bin count (≤ 0 → MATLAB default 64).
hgramOutOptional out-pointer; if non-null, receives ref's histogram as a 1×nbins double row (= imhist(ref, nbins)', MATLAB's 2nd output).
mrMemory resource (nullptr → process default).
Returns
Matched image, same class as I.
See also
histeq

◆ imhmax()

Value nk::image::imhmax ( const Value & I,
double h,
int conn,
std::pmr::memory_resource * mr = nullptr )

H-maxima transform (J = imhmax(I, h, conn)).

Suppresses regional maxima shallower than h: \( \text{imhmax}(I, h) = \text{imreconstruct}(I - h, I,\ \text{conn}) \).

Parameters
IInput image.
hSuppression threshold.
connConnectivity.
mrMemory resource (nullptr → process default).
Returns
H-maxima image.
See also
imhmin, imextendedmax

◆ imhmin()

Value nk::image::imhmin ( const Value & I,
double h,
int conn,
std::pmr::memory_resource * mr = nullptr )

H-minima transform (J = imhmin(I, h, conn)) — dual of imhmax.

Parameters
IInput image.
hSuppression threshold.
connConnectivity.
mrMemory resource (nullptr → process default).
Returns
H-minima image.
See also
imhmax

◆ imimposemin()

Value nk::image::imimposemin ( const Value & I,
const Value & BW,
int conn,
std::pmr::memory_resource * mr = nullptr )

Minima imposition (J = imimposemin(I, BW, conn)).

Modifies grayscale I so its only regional minima sit at the marker pixels in BW. Soille's reconstruction-by-erosion recipe. Useful as the pre-processing step for marker-controlled watershed.

Parameters
IGrayscale image.
BWLOGICAL marker mask.
connConnectivity.
mrMemory resource (nullptr → process default).
Returns
Image with imposed minima.
See also
imregionalmin, imreconstruct

◆ imkeepborder()

Value nk::image::imkeepborder ( const Value & BW,
int conn,
std::pmr::memory_resource * mr = nullptr )

Keep only border-touching components (J = imkeepborder(BW, conn)) — dual of imclearborder.

Parameters
BWBinary input.
connConnectivity.
mrMemory resource (nullptr → process default).
Returns
Binary image with only rim-connected components.

◆ imlincomb()

Value nk::image::imlincomb ( const std::vector< double > & coefs,
const std::vector< Value > & images,
ValueType output_class,
std::pmr::memory_resource * mr = nullptr )

Linear combination of images (Z = imlincomb(coefs, images, class)).

Computes \( Z = \sum_k c_k\,X_k \) and casts the result to output_class (with saturation for integer classes). All images must share the same size.

Parameters
coefs1-D vector of weights \( c_k \).
imagesVector of input images, same length as coefs.
output_classTarget class for the result.
mrMemory resource (nullptr → process default).
Returns
Linear combination cast to output_class.
Exceptions
Errorif sizes disagree or the vectors are empty.

◆ immse()

Value nk::image::immse ( const Value & A,
const Value & B,
std::pmr::memory_resource * mr = nullptr )

Mean squared error (err = immse(A, B)).

\( \text{MSE} = \dfrac{1}{N}\sum_i (A_i - B_i)^2 \).

Parameters
AFirst image.
BSecond image (same shape as A).
mrMemory resource (nullptr → process default).
Returns
Real scalar MSE.
See also
psnr, ssim

◆ immultiply()

Value nk::image::immultiply ( const Value & x,
const Value & y,
std::pmr::memory_resource * mr = nullptr )

Saturating element-wise multiplication (Z = immultiply(X, Y)).

Parameters
xFirst image (or scalar).
ySecond image (or scalar).
mrMemory resource (nullptr → process default).
Returns
Image of the same class and shape as X.
See also
imadd, imdivide

◆ imnlmfilt()

void nk::image::imnlmfilt ( const Value & I,
double dos,
int swsize,
int cwsize,
Value & J_out,
double & est_out,
std::pmr::memory_resource * mr = nullptr )

Non-local means denoising ([J, estDoS] = imnlmfilt(I, ...)).

Buades–Coll–Morel (2005) NLM filter — replace each pixel with a weighted average of similar-patch pixels within a search window. MATLAB uses the box-blur patch-distance variant (mean squared pixel diff over the comparison window), not the Gaussian-weighted original.

for each pixel p: for each q in S×S search window around p: d² = (1/|N|) Σ_{x∈N} (I(p+x) − I(q+x))² w(p, q) = exp(−d² / h²) J(p) = Σ_q w·I(q) / Σ_q w

The centre weight w(p, p) is set to the maximum non-self weight (Buades' "max-trick") to avoid the self-similarity blowup.

Default DegreeOfSmoothing h is the Immerkaer-1996 noise estimate: |Laplacian(I)| · √(π/2) / (6·(W−2)·(H−2))

Reference: [1] A. Buades, B. Coll, J.-M. Morel, "A Non-Local Algorithm for Image Denoising", CVPR 2005. [2] J. Immerkaer, "Fast Noise Variance Estimation", CVIU 64(2), 1996.

Grayscale 2-D inputs only here; the RGB / colour path (Euclidean distance summed across channels) is deferred.

Image must be at least 21×21 (MATLAB's hard minimum). SearchWindowSize and ComparisonWindowSize must be odd positive integers; CWS ≤ SWS ≤ min(H, W).

Output class equals input class.

Parameters
I2-D grayscale image.
dosDegreeOfSmoothing h (negative → use Immerkaer estimate).
swsizeSearchWindowSize (default 21).
cwsizeComparisonWindowSize (default 5).
[out]J_outDenoised image.
[out]est_outEffective h used (estimated if input was negative).
mrMemory resource (nullptr → process default).

◆ imnoise()

Value nk::image::imnoise ( ::nk::ops::RngContext & rng,
const Value & I,
const std::string & mode,
const Value & p1,
const Value & p2,
std::pmr::memory_resource * mr = nullptr )

Add synthetic noise to an image (J = imnoise(I, mode, p1, p2)).

Modes:

mode params output
"gaussian" m = 0, var = 0.01 J = I + m + sqrt(var)·N(0, 1)
"localvar" V (variance map) J = I + sqrt(V)·N(0, 1)
"salt & pepper" density d = 0.05 fraction d set to {0, 1}
"speckle" var = 0.04 J = I + I·N(0, var)
"poisson" (no params) Poisson with mean = I·scale

Image is treated as unit-range [0, 1] internally; output is cast back to the input class with saturation.

Parameters
IInput image.
modeOne of the strings above.
p1First parameter (see table).
p2Second parameter (see table).
mrMemory resource (nullptr → process default).
Returns
Noisy image, same class as I.

◆ imopen()

Value nk::image::imopen ( const Value & I,
const Value & SE,
std::pmr::memory_resource * mr = nullptr )

Morphological opening (J = imopen(I, SE) = imdilate(imerode(I, SE), SE)).

Parameters
IInput image.
SEStructuring element.
mrMemory resource (nullptr → process default).
Returns
Opened image.
See also
imclose

◆ imoverlay()

Value nk::image::imoverlay ( const Value & I,
const Value & BW,
const Value & color,
std::pmr::memory_resource * mr = nullptr )

Paint a binary mask onto an image with a colour (J = imoverlay(I, BW, color)).

Foreground pixels of BW are replaced with color (1×3 RGB triple). Native scale: 0..255 for uint8 input, 0..1 for float input. Grayscale I is replicated to 3 channels first. Output is always H × W × 3 uint8.

Parameters
IGrayscale or RGB image.
BWLogical mask of the same H × W.
color1×3 RGB triple.
mrMemory resource (nullptr → process default).
Returns
H × W × 3 uint8 image.

◆ impyramid()

Value nk::image::impyramid ( const Value & A,
const std::string & type,
std::pmr::memory_resource * mr = nullptr )

Burt–Adelson image pyramid step (B = impyramid(A, type)).

Implements one level of the classic Burt–Adelson Gaussian pyramid with a 5-tap separable kernel [0.05 0.25 0.4 0.25 0.05] and replicate boundary handling. 3-D inputs are processed per-channel.

Parameters
AInput image.
type"reduce" (output ceil(M/2)×ceil(N/2) after low-pass) or "expand" (output (2M-1)×(2N-1) after zero-stuff).
mrMemory resource (nullptr → process default).
Returns
Downsampled / upsampled image.

◆ imquantize()

Value nk::image::imquantize ( const Value & I,
const Value & levels,
std::pmr::memory_resource * mr = nullptr )

Quantise into N+1 classes (L = imquantize(I, levels)).

levels is an N-vector of thresholds; output is the class index (1-based) of each pixel.

Parameters
IInput image.
levelsSorted threshold vector (length N).
mrMemory resource (nullptr → process default).
Returns
Integer class map (1-based, same shape as I).
See also
multithresh

◆ imread()

Value nk::image::imread ( const std::string & path,
std::pmr::memory_resource * mr = nullptr )

Read an image from disk (A = imread(path)).

Decoded element type is uint8 or uint16 (preserving native bit depth). Channel count depends on the source file:

  • grayscale → H×W (uint8 or uint16).
  • RGB → H×W×3 (channels R, G, B).
  • RGBA → H×W×4 (channels R, G, B, A).
Parameters
pathFilesystem path (relative or absolute).
mrMemory resource (nullptr → process default).
Returns
uint8 image Value.
Exceptions
Erroron missing file or unsupported / corrupt format.
See also
imwrite, imfinfo

◆ imreconstruct()

Value nk::image::imreconstruct ( const Value & marker,
const Value & mask,
int conn,
std::pmr::memory_resource * mr = nullptr )

Morphological reconstruction by dilation (J = imreconstruct(marker, mask, conn)).

Iteratively dilates marker and caps element-wise against mask until stable: \( J_{k+1} = \min(\text{imdilate}(J_k, SE),\ \text{mask}) \), \( J_0 = \text{marker} \). Works on binary or grayscale inputs. marker <= mask element-wise is required (we clip up-front to enforce).

Parameters
markerSeed image.
maskUpper-bound image (marker <= mask).
connConnectivity (4 or 8).
mrMemory resource (nullptr → process default).
Returns
Reconstructed image, same shape as marker.
See also
imfill_holes, imhmax, imclearborder

◆ imreducehaze()

Value nk::image::imreducehaze ( const Value & I,
double amount,
const std::string & method,
const Value & atmospheric_light,
const std::string & contrast_enhancement,
double boost_amount,
Value & t_out,
Value & L_out,
std::pmr::memory_resource * mr = nullptr )

Dark-channel-prior haze removal ([J, T, L] = imreducehaze(I, amount, ...)).

Single-image dehazing via the dark-channel-prior atmospheric model (He-Sun-Tang 2011, "Single Image Haze Removal Using Dark Channel Prior", IEEE TPAMI 33(12)). Two algorithm flavours:

  • "simpledcp" (default) — per-pixel dark channel D(x) = min_c I_c(x); atmospheric light estimated by 5-level quadtree decomposition (Dubok et al. 2014, ICIP) on the dark channel; transmission map refined via guided filter with a 5×5 neighbourhood and ε=0.01; ω=0.9 (mild residual haze).
  • "approxdcp" — patched dark channel via min-erosion with square strel of size ceil(min(H,W)/400·15); atmospheric light estimated from the 0.1% brightest dark-channel pixels; transmission map computed via 1 - imopen(A/L, strel) and refined with guided filter (radius ceil(min(H,W)/50), ε=1e-4, subsample=min(4, radius)); ω=0.95.

Atmospheric-light estimation:

  • When atmospheric_light is Value::Empty and method is "simpledcp": quadtree on min_c I_c eroded by the strel, picking the brightest-mean quadrant for 5 levels, then the pixel in that quadrant with minimum Euclidean distance to [1, 1, 1]. For images smaller than 64×64 the quadtree is skipped and the full image is searched.
  • When atmospheric_light is Value::Empty and method is "approxdcp": take the 0.1% brightest pixels of the dark channel; among those, pick the pixel with the highest grayscale luminance.

Scene radiance: R(x) = L + (I(x) - L) / max(t̃(x), t₀) with t̃ = 1 - ω·(1-t), t₀ = 0.1. Final blend by user amount: t' = min(1, t̃ + amount), J = R·t' + L·(1-t').

Post-processing (contrast_enhancement):

  • "global" (default) — A.^0.75, mat2gray, stretchlim [0.001 0.999], imadjust with clip + 0.8·(max(clip,mean)
    • clip)
    .
  • "boost" — J·(1 + amount·boost_amount·(1-T)).
  • "none" — no post-processing.

Outputs:

  • J — dehazed image, same class and shape as I. For uint8/uint16 returns saturated im2*; for single / double returns clipped to [0, 1].
  • T — haze thickness (1 - t), DOUBLE H×W.
  • L — estimated atmospheric light. DOUBLE 1×3 for RGB, DOUBLE scalar for grayscale.

Returns only J (the typed entry-point packs T and L into t_out / L_out references). When amount == 0, the function short-circuits to return the input unchanged with empty T / L.

Parameters
IH × W (grayscale) or H × W × 3 (RGB), uint8/uint16/single/ double.
amount∈ [0, 1]. 1 = full removal.
method"simpledcp" (def) / "approxdcp".
atmospheric_lightEmpty → estimate. Otherwise 1×3 (RGB) or scalar (grayscale) DOUBLE in [0, 1].
contrast_enhancement"global" (def) / "boost" / "none".
boost_amount∈ [0, 1] for "boost", default 0.1.
t_out(output) Haze thickness, DOUBLE H×W.
L_out(output) Atmospheric light, DOUBLE 1×3 (RGB) or scalar (gray).
mrMemory resource (nullptr → default).
Returns
Dehazed image J.

◆ imregionalmax()

Value nk::image::imregionalmax ( const Value & I,
int conn,
std::pmr::memory_resource * mr = nullptr )

Regional maxima mask (J = imregionalmax(I, conn)).

Connected pixel groups whose neighbours are all strictly smaller. Standard formula: \( \text{regmax}(I) = (I - \text{imreconstruct}(I - 1, I)) > 0 \).

Parameters
IInput image.
connConnectivity.
mrMemory resource (nullptr → process default).
Returns
LOGICAL maxima mask, same shape as I.
See also
imregionalmin, imextendedmax

◆ imregionalmin()

Value nk::image::imregionalmin ( const Value & I,
int conn,
std::pmr::memory_resource * mr = nullptr )

Regional minima mask (J = imregionalmin(I, conn)).

Dual of imregionalmax via image inversion (typeMax - I for unsigned, -I for floats).

Parameters
IInput image.
connConnectivity.
mrMemory resource (nullptr → process default).
Returns
LOGICAL minima mask.
See also
imregionalmax

◆ imresize() [1/2]

Value nk::image::imresize ( const Value & A,
double scale,
const std::string & method,
std::pmr::memory_resource * mr = nullptr )

Resample an image to a new size by a uniform scale factor (B = imresize(A, scale, method)).

Parameters
AInput image (H×W or H×W×C).
scalePositive scale factor (> 1 enlarges, < 1 shrinks).
method"nearest" or "bilinear" (default).
mrMemory resource (nullptr → process default).
Returns
Resampled image; element type preserved.
See also
imcrop, imrotate

◆ imresize() [2/2]

Value nk::image::imresize ( const Value & A,
size_t outH,
size_t outW,
const std::string & method,
std::pmr::memory_resource * mr = nullptr )

Resample an image to an explicit output size (B = imresize(A, [outH outW], method)).

Same as the scale-factor overload but with explicit target rows / cols.

Parameters
AInput image (H×W or H×W×C).
outHOutput row count.
outWOutput column count.
method"nearest" or "bilinear" (default).
mrMemory resource (nullptr → process default).
Returns
Resampled image; element type preserved.
See also
imcrop, imrotate

◆ imresize3() [1/2]

Value nk::image::imresize3 ( const Value & V,
double scale,
const std::string & method,
bool antialias,
std::pmr::memory_resource * mr = nullptr )

Resample a 3-D volume by a uniform scale factor (B = imresize3(V, scale, ...)).

See size-vector overload.

◆ imresize3() [2/2]

Value nk::image::imresize3 ( const Value & V,
size_t outR,
size_t outC,
size_t outD,
const std::string & method,
bool antialias,
std::pmr::memory_resource * mr = nullptr )

Resample a 3-D volume to a new size (B = imresize3(V, scale|[r c d], method, ...)).

Separable 1-D resampling along rows / cols / planes using the same kernel and boundary convention as MATLAB R2025b imresize: 1-indexed centered coordinate u = o/scale + 0.5·(1 − 1/scale), mirror boundary aux = [1..N, N..1] of cycle 2N, P = ⌈kernel_width⌉ + 2 taps per output sample, weights normalized to sum to 1. With antialias = true and a shrink (scale < 1) the kernel is stretched via h(x) = scale · k(scale · x) (MATLAB's anti-aliasing).

References:

  • Keys 1981 — Catmull-Rom cubic (default 'cubic', a = −0.5).
  • Duchon 1979 — Lanczos windowed-sinc kernels.
  • Smith 1995 ("A pixel is not a little square…") — pixel-center coordinate convention.
Parameters
V3-D numeric volume.
outROutput row count.
outCOutput column count.
outDOutput plane count.
method"nearest", "box", "triangle" (= "linear"), "cubic" (default), "lanczos2", or "lanczos3".
antialiastrue to enable anti-aliasing when shrinking.
mrMemory resource (nullptr → process default).
Returns
Resampled volume; element type preserved with clip.

◆ imrotate()

Value nk::image::imrotate ( const Value & A,
double angle,
const std::string & method,
const std::string & bbox,
std::pmr::memory_resource * mr = nullptr )

Rotate an image counter-clockwise (B = imrotate(A, angle, method, bbox)).

Parameters
AInput image.
angleRotation in degrees, CCW positive.
method"nearest" or "bilinear" (default).
bbox"loose" (default — expand to fit rotated extent) or "crop" (keep input dims; clip rotated pixels that fall outside).
mrMemory resource (nullptr → process default).
Returns
Rotated image; pixels outside source filled with 0.

◆ imrotate3()

Value nk::image::imrotate3 ( const Value & V,
double angle_deg,
double Wx,
double Wy,
double Wz,
const std::string & method,
const std::string & bbox,
double fill,
std::pmr::memory_resource * mr = nullptr )

Rotate a 3-D volume around an arbitrary axis (B = imrotate3(V, angle, W, method, bbox, FillValues=v)).

Rotates V by angle degrees counterclockwise (right-hand rule) around the axis vector W = [Wx Wy Wz] passing through the centre of the volume. Uses the Rodrigues rotation matrix and applies an inverse-warp on each output voxel:

(xs, ys, zs) = inCentre + R · ((xo, yo, zo) − outCentre)

where the spatial X / Y / Z = col / row / page (MATLAB convention). Out-of-bounds source samples evaluate to fill.

References:

  • Rodrigues 1840 — axis-angle rotation matrix.
  • Keys 1981 — Catmull-Rom tricubic kernel.
Parameters
V3-D numeric volume.
angle_degRotation in degrees (CCW, right-hand rule).
Wx,Wy,WzComponents of the axis vector (need not be unit).
method"nearest", "linear" (default), or "cubic".
bbox"loose" (default — expand to fit rotated extent) or "crop" (keep input dims).
fillOut-of-bounds fill value (default 0).
mrMemory resource (nullptr → process default).
Returns
Rotated volume; element type preserved.

◆ imsharpen()

Value nk::image::imsharpen ( const Value & I,
double radius,
double amount,
double threshold,
std::pmr::memory_resource * mr = nullptr )

Unsharp masking (B = imsharpen(I, radius, amount, threshold)).

high = I - imgaussfilt(I, radius); mask = |high| ≥ threshold · max|high|; B = saturate(I + amount · mask · high).

Defaults: radius = 1, amount = 0.8, threshold = 0.

Parameters
IInput image.
radiusGaussian radius in pixels.
amountSharpening strength (positive scalar).
thresholdThreshold on |high| relative to its max.
mrMemory resource (nullptr → process default).
Returns
Sharpened image, same class as I.

◆ imsmooth()

Value nk::image::imsmooth ( const Value & I,
const std::string & name,
double sigma,
std::pmr::memory_resource * mr = nullptr )

Octave-image style smoothing dispatcher (J = imsmooth(I, name, sigma)).

Currently supports only "Gaussian". 1-D-separable σ-Gaussian, kernel half-width ceil(3σ), default σ = 0.5, symmetric boundary, computed in double then cast back to the input class. RGB inputs are processed per-channel.

Parameters
IInput image.
nameSmoothing kernel name ("Gaussian").
sigmaGaussian σ. Default 0.5.
mrMemory resource (nullptr → process default).
Returns
Smoothed image, same class as I.
Exceptions
ErrorUnknown smoothing name.

◆ imsplit()

void nk::image::imsplit ( const Value & I,
std::vector< Value > & planes,
std::pmr::memory_resource * mr = nullptr )

Split a multi-plane image into per-plane Values (imsplit(I, planes)).

Splits an H × W × P volume into P planes (H × W each). For 2-D input returns a single H × W copy in planes[0]. planes is resized to P; output planes share the input's class.

Parameters
IInput image.
planesOutput vector (resized in-place).
mrMemory resource (nullptr → process default).

◆ imsubtract()

Value nk::image::imsubtract ( const Value & x,
const Value & y,
std::pmr::memory_resource * mr = nullptr )

Saturating image subtraction (Z = imsubtract(X, Y)).

Same semantics as imadd but for Z = X - Y.

Parameters
xFirst image (or scalar).
ySecond image (or scalar).
mrMemory resource (nullptr → process default).
Returns
Image of the same class and shape as X.
See also
imadd, imabsdiff

◆ imtophat()

Value nk::image::imtophat ( const Value & I,
const Value & SE,
std::pmr::memory_resource * mr = nullptr )

White top-hat (J = imtophat(I, SE) = I - imopen(I, SE)).

Highlights bright structures smaller than SE on a dark background. Output saturates to the input class.

Parameters
IInput image.
SEStructuring element.
mrMemory resource (nullptr → process default).
Returns
Top-hat image.
See also
imbothat, imopen

◆ imtranslate()

Value nk::image::imtranslate ( const Value & A,
double dx,
double dy,
std::pmr::memory_resource * mr = nullptr )

Shift an image by an arbitrary (dx, dy) translation (B = imtranslate(A, [dx dy])).

Half-pixel shifts use bilinear interpolation; integer shifts use a fast nearest-neighbour copy. Same dims as input; out-of-source pixels filled with 0.

Parameters
AInput image.
dxShift along columns (sub-pixel allowed).
dyShift along rows.
mrMemory resource (nullptr → process default).
Returns
Translated image, same shape and class as A.
See also
imrotate, imresize

◆ imwrite()

void nk::image::imwrite ( const Value & A,
const std::string & path,
std::pmr::memory_resource * mr = nullptr )

Write an image to disk (imwrite(A, path)).

Encodes an H×W or H×W×{1, 3, 4} uint8 array. Format inferred from the path extension:

Extension Format
.png PNG
.bmp BMP
.tga TGA
.jpg, .jpeg JPEG (q=90)
Parameters
AImage (uint8, 1/3/4 channels).
pathOutput path; extension picks the encoder.
mrMemory resource (nullptr → process default).
Exceptions
Erroron unsupported extension or write failure.
See also
imread

◆ imwriteToBytes()

std::string nk::image::imwriteToBytes ( const Value & A,
const std::string & ext,
std::pmr::memory_resource * mr = nullptr )

Encode an image to in-memory bytes (companion to imwrite).

Used by the engine entry so writes go through the VFS — works on the virtual AND real filesystem. ext is the lowercase extension WITHOUT a dot ("png" | "bmp" | "tga" | "jpg" | "jpeg"). TIFF is handled separately by writeTiffToBytes().

Exceptions
Erroron unsupported extension or encode failure.

◆ ind2gray()

Value nk::image::ind2gray ( const Value & idx,
const Value & map,
std::pmr::memory_resource * mr = nullptr )

Indexed → grayscale (I = ind2gray(idx, map)).

Pulls the luminance value out of map for each entry in idx. Pass Value::Empty for map to use gray(N) where N = max(idx).

Parameters
idxIndex image.
mapColormap.
mrMemory resource (nullptr → process default).
Returns
Grayscale image.
See also
gray2ind

◆ ind2rgb()

Value nk::image::ind2rgb ( const Value & idx,
const Value & map,
std::pmr::memory_resource * mr = nullptr )

Indexed → RGB (RGB = ind2rgb(idx, map)).

Float idx is 1-based; integer idx is 0-based. Out-of-range entries clip to the first / last colormap row.

Parameters
idxIndex image.
mapColormap.
mrMemory resource (nullptr → process default).
Returns
M × N × 3 DOUBLE image.
See also
gray2ind, ind2gray

◆ integralBoxFilter()

Value nk::image::integralBoxFilter ( const Value & I,
int fH,
int fW,
double normFactor,
std::pmr::memory_resource * mr = nullptr )

2-D box filter on a precomputed integral image (B = integralBoxFilter(I, [fH fW], normFactor)).

Computes the sum of underlying pixels in an fH × fW window using four lookups in the integral image, then multiplies by normFactor. Output size is (H - fH + 1) × (W - fW + 1) where the integral image I has shape (H+1) × (W+1) — only the fully-supported (no-boundary) region is returned, matching MATLAB. 3-D input (H+1) × (W+1) × C is processed per-channel.

normFactor is a MATLAB-style multiplier: the box sum is multiplied by it. The default (set by the adapter) is 1/(fH·fW), giving the mean; pass 1 for the raw sum.

Parameters
IIntegral image (output of integralImage).
fHBox height (positive odd integer).
fWBox width (positive odd integer).
normFactorMultiplier applied to each box sum (1/(fH·fW) → mean).
mrMemory resource (nullptr → process default).
Returns
Filtered values, size (H - fH + 1) × (W - fW + 1)[ × C].
See also
integralImage, imboxfilt

◆ integralBoxFilter3()

Value nk::image::integralBoxFilter3 ( const Value & I,
int fH,
int fW,
int fP,
double normFactor,
std::pmr::memory_resource * mr = nullptr )

3-D box filter on a precomputed integral volume (B = integralBoxFilter3(A, [fH fW fP], NormalizationFactor, n)).

Given the summed-volume table A of shape (H+1) × (W+1) × (D+1) (output of integralImage3), computes the sum of underlying voxels in an fH × fW × fP window using eight lookups (inclusion-exclusion), then multiplies by normFactor. Output size is (H − fH + 1) × (W − fW + 1) × (D − fP + 1) — only the fully-supported (no-boundary) core, matching MATLAB.

Unlike the 2-D integralBoxFilter (whose normFactor is a divisor), here normFactor is the MATLAB-style multiplier: the box sum is multiplied by it. The default (set by the adapter) is 1 / (fH·fW·fP), giving the mean; pass 1 for the raw sum.

Parameters
IIntegral volume (output of integralImage3).
fHBox height (positive odd integer).
fWBox width (positive odd integer).
fPBox depth (positive odd integer).
normFactorMultiplier applied to each box sum.
mrMemory resource (nullptr → process default).
Returns
Filtered volume, size (H−fH+1)×(W−fW+1)×(D−fP+1).
See also
integralImage3, imboxfilt3, integralBoxFilter

◆ integralImage()

Value nk::image::integralImage ( const Value & I,
std::pmr::memory_resource * mr = nullptr )

Summed-area table (J = integralImage(I)).

Output is (M+1) × (N+1) DOUBLE with a leading zero row and column, so the rectangle sum \( \sum_{r=r_0}^{r_1} \sum_{c=c_0}^{c_1} I \) equals \( J[r_1+1, c_1+1] - J[r_0, c_1+1] - J[r_1+1, c_0] + J[r_0, c_0] \).

Parameters
IInput image.
mrMemory resource (nullptr → process default).
Returns
(M+1) × (N+1) integral image.
See also
integralImage3

◆ integralImage3()

Value nk::image::integralImage3 ( const Value & V,
std::pmr::memory_resource * mr = nullptr )

3-D summed-volume table (J = integralImage3(V)).

Output is (M+1) × (N+1) × (P+1) DOUBLE with a leading zero plane, row, and column. Direct 3-D extension of integralImage.

Parameters
VInput volume.
mrMemory resource (nullptr → process default).
Returns
(M+1) × (N+1) × (P+1) integral volume.
See also
integralImage

◆ intlut()

Value nk::image::intlut ( const Value & A,
const Value & LUT,
std::pmr::memory_resource * mr = nullptr )

Apply a look-up table to an integer image (B = intlut(A, LUT)).

A must be UINT8, UINT16, or INT16. LUT must have:

  • 256 elements for UINT8 input.
  • 65536 elements for UINT16 / INT16 input.

For INT16, the index is A(i) + 32768. Output class equals class(LUT).

Parameters
AInteger image.
LUTLookup table vector.
mrMemory resource (nullptr → process default).
Returns
Image with LUT applied.
Exceptions
ErrorWrong LUT length or non-integer input.

◆ iptnum2ordinal()

Value nk::image::iptnum2ordinal ( double n,
std::pmr::memory_resource * mr = nullptr )

English ordinal-form string (s = iptnum2ordinal(n)).

1..20 return English words ("first" … "twentieth"); 21+ use suffix form ("21st", "22nd", "23rd", "24th", …).

Parameters
nPositive integer (non-integer rejected).
mrMemory resource (nullptr → process default).
Returns
CHAR Value.
Exceptions
ErrorNon-integer or non-positive n.

◆ isbw()

Value nk::image::isbw ( const Value & BW,
const std::string & mode,
std::pmr::memory_resource * mr = nullptr )

Binary-image predicate (tf = isbw(BW, mode)).

  • mode = "logical" (default): requires class LOGICAL.
  • mode = "non-logical": accepts numeric classes whose values are all 0 or 1 (no NaN).

Spatial check: 2-D or M × N × 1 × K with pages == 1.

Parameters
BWInput image.
mode"logical" or "non-logical".
mrMemory resource (nullptr → process default).
Returns
LOGICAL scalar.
See also
isgray, isind, isrgb

◆ iscolormap()

Value nk::image::iscolormap ( const Value & cmap,
std::pmr::memory_resource * mr = nullptr )

Colormap-shape predicate (tf = iscolormap(cmap)).

True iff cmap is a real, float (SINGLE / DOUBLE) 2-D matrix with exactly 3 columns and >= 1 row. The [0, 1] range is not enforced (matches Octave behaviour).

Parameters
cmapCandidate colormap.
mrMemory resource (nullptr → process default).
Returns
LOGICAL scalar.

◆ isgray()

Value nk::image::isgray ( const Value & I,
std::pmr::memory_resource * mr = nullptr )

Grayscale-image predicate (tf = isgray(I)).

True if I is plausibly grayscale: 2-D or M × N × 1 × K, and either an integer-class image (UINT8 / UINT16 / INT16) or a float image whose values lie in [0, 1] or are NaN (not all NaN).

Parameters
IInput image.
mrMemory resource (nullptr → process default).
Returns
LOGICAL scalar.
See also
isbw, isrgb

◆ isind()

Value nk::image::isind ( const Value & I,
std::pmr::memory_resource * mr = nullptr )

Indexed-image predicate (tf = isind(I)).

True if I is plausibly indexed: 2-D or M × N × 1 × K, and either UINT8 / UINT16 or a float image whose values are positive integers.

Parameters
IInput image.
mrMemory resource (nullptr → process default).
Returns
LOGICAL scalar.
See also
isgray, gray2ind

◆ isrgb()

Value nk::image::isrgb ( const Value & I,
std::pmr::memory_resource * mr = nullptr )

RGB-image predicate (tf = isrgb(I)).

True if I is plausibly RGB: M × N × 3 (or M × N × 3 × K), and either an integer-class image or a float image with values in [0, 1] (not all NaN).

Parameters
IInput image.
mrMemory resource (nullptr → process default).
Returns
LOGICAL scalar.
See also
isgray

◆ jaccard()

Value nk::image::jaccard ( const Value & A,
const Value & B,
std::pmr::memory_resource * mr = nullptr )

Intersection-over-union (j = jaccard(BW1, BW2)).

j = |A ∩ B| / |A ∪ B|. Same input semantics as dice. Related by d = 2j / (1 + j).

Parameters
ASame-sized binary mask.
BSame-sized binary mask.
mrMemory resource (nullptr → process default).
Returns
Scalar in [0, 1].
See also
dice

◆ lab2double()

Value nk::image::lab2double ( const Value & lab,
std::pmr::memory_resource * mr = nullptr )

Cast Lab image to DOUBLE (labd = lab2double(lab)).

Parameters
labInput Lab.
mrMemory resource.
Returns
DOUBLE Lab in canonical scale.
See also
lab2single, lab2uint8, lab2uint16

◆ lab2rgb()

Value nk::image::lab2rgb ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

CIE L*a*b* → sRGB (inverse of rgb2lab).

Parameters
xLab image / colormap.
mrMemory resource.
Returns
sRGB image / colormap.

◆ lab2single()

Value nk::image::lab2single ( const Value & lab,
std::pmr::memory_resource * mr = nullptr )

Cast Lab image to SINGLE (labs = lab2single(lab)).

Parameters
labInput Lab.
mrMemory resource.
Returns
SINGLE Lab in canonical scale.

◆ lab2uint16()

Value nk::image::lab2uint16 ( const Value & lab,
std::pmr::memory_resource * mr = nullptr )

Cast Lab image to UINT16 (labu = lab2uint16(lab)).

Parameters
labInput Lab.
mrMemory resource.
Returns
UINT16 Lab with offset 32768.

◆ lab2uint8()

Value nk::image::lab2uint8 ( const Value & lab,
std::pmr::memory_resource * mr = nullptr )

Cast Lab image to UINT8 (labu = lab2uint8(lab)).

Parameters
labInput Lab.
mrMemory resource.
Returns
UINT8 Lab with offset 128.

◆ lab2xyz()

Value nk::image::lab2xyz ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

CIE L*a*b* → CIE XYZ (inverse of xyz2lab).

Parameters
xLab image / colormap.
mrMemory resource.
Returns
XYZ image / colormap.

◆ label2idx()

Value nk::image::label2idx ( const Value & L,
std::pmr::memory_resource * mr = nullptr )

Group label-image pixels into per-label index lists (idx = label2idx(L)).

Returns a column cell array. Entry k is a column vector of 1-based linear indices of all pixels with label k. Label 0 (background) is excluded.

Parameters
LInteger-typed label image.
mrMemory resource (nullptr → process default).
Returns
Cell array of length max(L), each entry a column of indices.

◆ label2rgb()

Value nk::image::label2rgb ( const Value & L,
const Value & cmap,
const Value & background,
std::pmr::memory_resource * mr = nullptr )

Colourise a labelled image (RGB = label2rgb(L, cmap, background)).

L is an H × W non-negative integer-valued matrix. cmap is an N × 3 colormap (DOUBLE in [0, 1]). Pixels with label == 0 take the background colour (default [1, 1, 1] = white).

Scope. The full signature accepts a colormap-name string or a function handle for cmap; both require a jet / hsv / etc. generator that we don't expose yet, so callers must pass an explicit N × 3 matrix here.

Parameters
LLabelled image.
cmapN × 3 colormap.
backgroundBackground colour (Value::Empty → white).
mrMemory resource (nullptr → process default).
Returns
H × W × 3 UINT8 colour image.

◆ labelmatrix()

Value nk::image::labelmatrix ( const Value & CC,
std::pmr::memory_resource * mr = nullptr )

Connected-component label matrix (L = labelmatrix(CC)).

Converts a bwconncomp struct into a label matrix the same size as the original image. Background pixels get label 0; component k (1-based) is written into all positions in CC.PixelIdxList{k}.

Output class follows MATLAB's rule:

  • NumObjects ≤ 255 → uint8
  • NumObjects ≤ 65535 → uint16
  • NumObjects ≤ 2³² - 1 → uint32
  • otherwise → double
Parameters
CCStruct from bwconncomp (must contain fields ImageSize, NumObjects, PixelIdxList).
mrMemory resource (nullptr → process default).
Returns
Label matrix sized like the source image.
See also
bwconncomp, cc2bw, label2rgb

◆ labeloverlay()

Value nk::image::labeloverlay ( const Value & A,
const Value & L,
const Value & colormap,
const std::string & color_assignment,
const Value & included_labels,
double transparency,
std::pmr::memory_resource * mr = nullptr )

Overlay a label / mask / categorical-index image on a 2-D base (B = labeloverlay(A, L, ...)).

Each non-zero label k > 0 is painted with a colour cmap(k+1, :) blended into the base via B = (1-α)·A + α·cmap, where α = 1 - transparency. Label 0 (or labels not in included_labels) passes the base through untouched. Output is always UINT8 (im2uint8 conversion at the end), and always 3-channel — grayscale A is replicated to RGB.

Pipeline (MATLAB R2025b labeloverlay.m + LabelColormapHelper.m):

  1. A = im2single(A). Replicate to 3 planes if grayscale.
  2. maxLabel = max(L(:)), totalLabels = maxLabel + 1.
  3. Resolve colormap:
    • "jet" (default) → cmap = jet(totalLabels).
    • Named string "hsv"/"parula"/... → feval(name, totalLabels).
    • Numeric Nx3 → used as-is.
  4. ColorAssignment:
    • Auto → NoShuffle if colormap was numeric, else Shuffle.
    • Shuffle → permute cmap rows by randperm(N) with MATLAB-canonical Mersenne-Twister seed 0 (bit-identical with rng('default'); randperm(N)).
    • ContrastingNeighbors → greedy graph colouring of the 8-connected adjacency graph of L.
  5. Build alphamap. If 0 ∈ included_labels: alphamap(k+1)=α for each included k. Else: insert a dummy row at the top of cmap (= cmap(1,:)) and 0 at the front of alphamap, so label 0 paints the base untouched.
  6. Per pixel: B(r,c,ch) = (1-alphamap(L+1)) · A(r,c,ch)
    • alphamap(L+1) · cmap(L+1,ch)
    .
  7. im2uint8(B).

Inputs may be grayscale (H × W) or RGB (H × W × 3). Logical masks are treated as a label matrix with values in {0, 1}. The categorical input form is not supported because categorical is a MATLAB OOP class (see policy §0); use a uint8/uint16 label matrix instead.

Parameters
ABase image (uint8/uint16/int16/single/double).
LLabel / mask matrix (non-negative integer).
colormapColormap. Pass Value::Empty for default "jet". May be a numeric Nx3 array or a string name ("jet", "hsv", "parula", "hot", "cool", "spring", "summer", "autumn", "winter", "gray", "bone", "copper", "pink", "lines", "colorcube", "prism", "flag").
color_assignment"auto" (def) / "shuffle" / "noshuffle" / "contrasting-neighbors".
included_labelsPass Value::Empty for default 1:maxLabel. Otherwise a vector of non-negative integers.
transparencyAlpha blend ∈ [0, 1]. 0 = opaque colour, 1 = invisible (default 0.5).
mrMemory resource (nullptr → process default).
Returns
UINT8 H × W × 3 overlay image.

◆ lin2rgb()

Value nk::image::lin2rgb ( const Value & A,
std::pmr::memory_resource * mr = nullptr )

Linear RGB → sRGB gamma forward (B = lin2rgb(A)).

Per-element piecewise: |x| <= 0.0031308 → 12.92 · x; otherwise sign(x) · (1.055 · |x|^(1/2.4) - 0.055). Same class-promotion rule as rgb2lin.

Parameters
AInput image / colormap.
mrMemory resource (nullptr → process default).
Returns
Gamma-encoded image / colormap.
See also
rgb2lin

◆ lines_cmap()

Value nk::image::lines_cmap ( int n,
std::pmr::memory_resource * mr = nullptr )

Axes-color-order palette (map = lines(n)).

Cycles the 7-row default colour order. n == 1 → [0 0 1].

Parameters
nRow count.
mrMemory resource.
Returns
n × 3 colormap.

◆ locallapfilt()

Value nk::image::locallapfilt ( const Value & I,
double sigma,
double alpha,
double beta,
int num_intensity_levels,
bool process_luminance,
std::pmr::memory_resource * mr = nullptr )

Edge-aware fast local Laplacian filtering (B = locallapfilt(I, sigma, alpha, beta, ...)).

Multi-scale image enhancement via per-pixel manipulation of the Laplacian pyramid coefficients. Operating points:

  • alpha > 1 → smoothing / detail suppression.
  • alpha < 1 → detail enhancement.
  • alpha = 1 → no detail change (then beta may still rescale).
  • beta < 1 → dynamic-range compression.
  • beta > 1 → dynamic-range expansion.
  • beta = 1 → preserve range.
  • sigma → magnitude of edges to consider. Larger = more coefficients treated as "details" (subject to alpha); smaller = more treated as "edges" (subject to beta).

Algorithm (Paris-Hasinoff-Kautz 2011, "Local Laplacian Filters", SIGGRAPH 2011, Eq. 4-7; fast-LLF accel by Aubry-Paris-Hasinoff- Kautz-Durand 2014, "Fast Local Laplacian Filters: Theory and Applications", ACM TOG 33(5)):

  1. Build Gaussian pyramid G_I of input I.
  2. For each intensity sample g_k ∈ {gmin, ..., gmax}: a. Remap R_k = remap(I, g_k, sigma, alpha, beta). b. Build Gaussian pyramid G_{R_k} of R_k. c. Compute Laplacian L_{R_k}[i] = G_{R_k}[i] - upsample(G_{R_k}[i+1]). d. For each pyramid level i and pixel p, accumulate: L_out[i](p) += k_w(G_I[i](p), g_k) · L_{R_k}[i](p) where k_w(v, g_k) = max(0, 1 - |v - g_k| / delta) is the triangular weight centred at g_k.
  3. Top level L_out[end] = G_I[end]. Collapse the Laplacian pyramid (L_out[i] += upsample(L_out[i+1])).

Remap function (per pixel):

d = I - g. If |d| <= sigma: I_new = g + sign(d) * sigma * (|d|/sigma)^alpha (detail). Else (|d| > sigma): I_new = g + sign(d) * (beta * (|d| - sigma) + sigma) (edge).

Pyramid filter is the 5×5 binomial separable kernel [1 4 6 4 1] / 16 (Burt-Adelson 1983, "The Laplacian Pyramid as a Compact Image Code") with replicate boundary. Upsampling inserts zero rows / cols then convolves with the same kernel scaled by 4 to preserve the local mean.

RGB input: ColorMode = "luminance" (default) computes the gray response Y = 0.298936·R + 0.587043·G + 0.114021·B, filters Y, then rescales the original RGB by the per-pixel ratio Y_filtered / Y_orig. ColorMode = "separate" filters each channel independently.

NumIntensityLevels: "auto" picks 50 for alpha < 0.1, linear ramp round(((50·0.9 - 16·0.1) - (50-16)·alpha) / 0.8) for 0.1 ≤ alpha < 0.9, and 16 otherwise. Higher = better quality at the cost of more pyramid builds.

Special cases:

  • alpha == 1 && beta == 1 → passthrough.
  • sigma == 0 && beta == 1 → passthrough.
  • Flat image (min == max) → passthrough.
  • numIntensityLevels == 1 → single remap at (min+max)/2.

Output class: matches input class. uint8/uint16 use saturating im2* conversions; int8/int16 likewise; single passes through with no clipping.

Parameters
IGrayscale H × W or RGB H × W × 3 image (single/uint8/uint16/int8/int16).
sigmaEdge-amplitude threshold (>= 0).
alphaDetail-curve exponent (> 0).
betaEdge-curve slope (>= 0, default 1).
num_intensity_levelsPyramid samples (-1 for auto).
process_luminancetrue = "luminance" mode for RGB, false = "separate" (per-channel).
mrMemory resource (nullptr → process default).
Returns
Filtered image, same class and shape as I.

◆ makelut()

Value nk::image::makelut ( FnHandle fun,
int n,
std::pmr::memory_resource * mr = nullptr )

Build a lookup table for bwlookup (lut = makelut(fun, n)).

Evaluates fun on every one of the 2^(n²) binary n × n neighbourhoods and returns the 2^(n²)-element column vector of results. n is 2 (length 16) or 3 (length 512). The neighbourhood for table index k (0-based) has, in column-major order, position i set to bit (k >> (n²−1−i)) & 1 — the inverse of the reshape(2^[nq−1:−1:0], n, n) weight kernel used by bwlookup, so bwlookup(BW, makelut(fun, n)) applies fun to each neighbourhood. fun receives a logical n × n matrix and returns a scalar; the output table is always DOUBLE.

Parameters
engEngine used to invoke the function handle.
funFunction handle: (logical n×n) → scalar.
nNeighbourhood size (2 or 3).
funCallback invoked once per n×n logical neighbourhood; must return a scalar. (The engine adapter binds it to the user function handle; core-free here.)
nNeighbourhood size (2 or 3).
mrMemory resource (nullptr → process default).
Returns
2^(n²) × 1 DOUBLE lookup table.
Exceptions
Errorn not 2 or 3, or fun returns a non-scalar.
See also
bwlookup, applylut

◆ mat2gray()

Value nk::image::mat2gray ( const Value & x,
double lo = std::numeric_limits< double >::quiet_NaN(),
double hi = std::numeric_limits< double >::quiet_NaN(),
std::pmr::memory_resource * mr = nullptr )

Linear rescale to [0, 1] DOUBLE (B = mat2gray(A, lo, hi)).

Maps [lo, hi] linearly to [0, 1] and clips. If lo / hi are NaN, they default to min(A) / max(A). Useful for visualising floating-point matrices.

Parameters
xInput matrix.
loLow intensity (NaN → auto = min(x)).
hiHigh intensity (NaN → auto = max(x)).
mrMemory resource (nullptr → process default).
Returns
DOUBLE image in [0, 1].
See also
im2double

◆ mean2()

Value nk::image::mean2 ( const Value & A,
std::pmr::memory_resource * mr = nullptr )

Mean of every element (m = mean2(A)).

2-D semantics: higher-dimensional inputs are treated as flat and averaged element-wise.

Parameters
AInput image.
mrMemory resource (nullptr → process default).
Returns
Scalar mean.
See also
std2

◆ medfilt2()

Value nk::image::medfilt2 ( const Value & I,
int rows = 3,
int cols = 3,
std::pmr::memory_resource * mr = nullptr )

2-D median filter (B = medfilt2(I, [m n])).

Default neighbourhood 3×3. Symmetric boundary.

Parameters
IInput image.
rowsNeighbourhood rows. Default 3.
colsNeighbourhood cols. Default 3.
mrMemory resource (nullptr → process default).
Returns
Filtered image, same class as I.
See also
medfilt3, ordfilt2

◆ medfilt3()

Value nk::image::medfilt3 ( const Value & V,
int M,
int N,
int P,
std::pmr::memory_resource * mr = nullptr )

3-D median filter (J = medfilt3(V, [M N P])).

Default 3×3×3 neighbourhood; sizes must be odd positive. Boundary is symmetric (mirror reflection) by default. Output class matches input. NB: only 'symmetric' padopt is supported in this first cut.

Parameters
VInput volume (3-D).
MNeighbourhood rows.
NNeighbourhood cols.
PNeighbourhood pages.
mrMemory resource (nullptr → process default).
Returns
Filtered volume, same class as V.
See also
medfilt2

◆ mmgradm()

Value nk::image::mmgradm ( const Value & I,
const Value & se_dil,
const Value & se_ero,
std::pmr::memory_resource * mr = nullptr )

Morphological gradient (G = mmgradm(I, se_dil, se_ero)).

Default: \( G = \text{imdilate}(I) - \text{imerode}(I) \) with elementary cross (diamond, radius 1). For LOGICAL inputs the subtraction collapses to dilate & ~erode.

Half-gradients:

  • mmgradm(I, Value::Empty, se_ero) → internal (-imerode).
  • mmgradm(I, se_dil, Value::Empty) → external (imdilate).
Parameters
IInput image.
se_dilDilation SE, or Value::Empty for internal half.
se_eroErosion SE, or Value::Empty for external half.
mrMemory resource (nullptr → process default).
Returns
Gradient image.

◆ modefilt()

Value nk::image::modefilt ( const Value & A,
int fH,
int fW,
const std::string & padopt,
std::pmr::memory_resource * mr = nullptr )

2-D mode filter (B = modefilt(A, [fH fW], padopt)).

Replaces each pixel with the most common value (mode) in an fH × fW window centred at that pixel. Ties are broken by the SMALLEST value (matches MATLAB's documented mode behaviour).

Tie-break note: MATLAB's modefilt MEX uses an undocumented order-dependent rule that diverges from base mode for some tied inputs (especially with zeros padding at image edges). nk follows the documented mode rule (smallest-wins-on-tie) which is deterministic and predictable.

Parameters
AInput image (UINT8/UINT16/INT/DOUBLE 2-D array). Float inputs are processed by binning unique values.
fHFilter height (positive odd integer).
fWFilter width (positive odd integer).
padopt"symmetric" (default), "replicate", or "zeros".
mrMemory resource (nullptr → process default).
Returns
Same-shape mode-filtered image, same class as A.
See also
medfilt2, imboxfilt

◆ modefilt3D()

Value nk::image::modefilt3D ( const Value & A,
int fH,
int fW,
int fD,
const std::string & padopt,
std::pmr::memory_resource * mr = nullptr )

3-D variant: modefilt(V, [fH fW fD], padopt).

Same algorithm extended over the third dimension. Default fD = 3 when called from MATLAB on a 3-D input.

◆ multissim()

Value nk::image::multissim ( const Value & A,
const Value & Iref,
int num_scales,
const std::vector< double > & scale_weights,
double sigma,
double dynamic_range,
std::vector< Value > * quality_maps_out,
std::pmr::memory_resource * mr = nullptr )

Multi-scale structural similarity index ([score, qmaps] = multissim(I, Iref, ...)).

Wang-Simoncelli-Bovik 2003 multi-scale SSIM, "Asilomar Conf. on Signals, Systems & Computers". Generalizes SSIM by averaging the contrast-and-structural component across a Gaussian pyramid and applying the full SSIM formula only at the coarsest scale.

Algorithm:

  1. For each scale i = 1 .. numScales - 1:
    • ssimmap_i = (2·σxy + C₂) / (σx² + σy² + C₂) (no luminance).
    • Mean over ssimmap_i, clamped to ≤ 1, raised to scaleWeights[i] (negative bases clamped to 0).
    • Lowpass with [1 1; 1 1] / 4 (replicate boundary).
    • Downsample by 2 (take rows/cols 1:2:end).
  2. At the coarsest scale, compute the full SSIM with luminance: (2·μx·μy + C₁)·(2·σxy + C₂) / ((μx² + μy² + C₁)·(σx² + σy² + C₂)).
  3. score = prod_i (mean(ssimmap_i)^scaleWeights[i]).

Local statistics use an N × N isotropic Gaussian filter with standard deviation sigma and N = 2·ceil(3·sigma) + 1 (so ≥ 99.7% of the kernel mass is included). Replicate boundary.

C₁ = (0.01·L)², C₂ = (0.03·L)², where L is the dynamic range (255 for uint8, 65535 for uint16/int16, 1 for single / double). dynamic_range = -1.0 activates the class default.

scaleWeights defaults to fspecial('gaussian', [1 numScales], 1) = a length-numScales Gaussian sample then normalised to sum to 1. Pass an empty std::vector to get the default; otherwise the vector is normalised internally to sum to 1.

Class support: uint8/uint16/int16/single/double. Image classes are promoted to SINGLE internally except double, which is computed in double. Output is SINGLE for single inputs, DOUBLE for double, otherwise SINGLE.

When quality_maps_out is non-null, the per-scale quality maps are written to it (length numScales, with qmaps[i] sized to match the i-th downsampled image).

Parameters
AFirst image (grayscale H × W).
IrefReference image (same class and size).
num_scalesPyramid depth (default 5).
scale_weightsPer-scale weights, length = num_scales. Empty → default Gaussian weights.
sigmaGaussian filter σ (default 1.5).
dynamic_rangeL (-1.0 = class default).
quality_maps_outOptional output: per-scale ssimmap.
mrMemory resource (nullptr → process default).
Returns
Scalar (SINGLE / DOUBLE) MS-SSIM score in (-1, 1] (1 = identical).

◆ multissim3()

Value nk::image::multissim3 ( const Value & V,
const Value & Vref,
int num_scales,
const std::vector< double > & scale_weights,
double sigma,
double dynamic_range,
std::vector< Value > * quality_maps_out,
std::pmr::memory_resource * mr = nullptr )

3-D multi-scale SSIM ([score, qmaps] = multissim3(V, Vref, ...)).

Volumetric extension of multissim. Per-scale SSIM with the same formula but with all spatial operations (Gaussian smoothing, 2 × 2 × 2 / 8 box lowpass, factor-2 downsample) applied along rows, columns, AND slices. The Gaussian filter is separable and applied as three successive 1-D convolutions along each spatial axis with filtSize = 2·ceil(3·sigma) + 1 (covers ≥99.7% of kernel mass). Replicate boundary.

Pipeline: identical to multissim except all dimensions are downsampled per scale.

Reference: Wang, Z., Simoncelli, E.P., & Bovik, A.C. (2003). Multiscale structural similarity for image quality assessment. Asilomar Conf. on Signals, Systems & Computers.

Parameters
VInput volume (H × W × D, grayscale).
VrefReference volume (same class and size).
num_scalesPyramid depth (default 5).
scale_weightsPer-scale weights (empty → default Gaussian weights).
sigmaGaussian σ (default 1.5).
dynamic_rangeL (-1.0 = class default).
quality_maps_outOptional output: per-scale ssim maps (length num_scales, each H_i × W_i × D_i DOUBLE).
mrMemory resource (nullptr → default).
Returns
Scalar score (DOUBLE for double inputs, SINGLE otherwise).

◆ multithresh()

std::tuple< Value, Value > nk::image::multithresh ( const Value & I,
int N,
std::pmr::memory_resource * mr = nullptr )

N-level Otsu ([thresh, em] = multithresh(I, N)).

Returns N thresholds and the global effectiveness metric.

Parameters
IInput image.
NNumber of thresholds.
mrMemory resource (nullptr → process default).
Returns
Tuple (thresh, em).
See also
graythresh

◆ nlfilter()

Value nk::image::nlfilter ( const Value & A,
std::size_t m,
std::size_t n,
FnHandle fun,
bool indexed,
std::pmr::memory_resource * mr = nullptr )

General sliding-neighbourhood operation (B = nlfilter(A, [m n], fun)).

For every pixel in A extracts the m × n window centred on that pixel (top-left bias for even sizes: pad rows above = floor((m-1)/2), below = ceil((m-1)/2); similarly cols) and passes it to fun. The result of fun(window) (a scalar) is written to B(i, j). Output class is the class of the FIRST fun invocation's return value, matching MATLAB's behaviour.

Padding. Default padval = 0. The 'indexed' form uses padval = 1 for single / double A, otherwise padval = 0.

Parameters
AInput image.
mNeighbourhood row count.
nNeighbourhood column count.
funCallback invoked once per m×n window; returns a scalar. (Engine adapter binds it to the user handle; core-free.)
indexedtrue → 'indexed' padding rule (see above).
mrMemory resource (nullptr → process default).
Returns
Filtered image, same H×W as A, class = output class of fun.

◆ normxcorr2()

Value nk::image::normxcorr2 ( const Value & templ,
const Value & img,
std::pmr::memory_resource * mr = nullptr )

Normalised cross-correlation (C = normxcorr2(template, img)).

Output is (M+m-1) × (N+n-1) DOUBLE in [-1, 1] (numerical noise outside this range is clamped to 0 by the inf/NaN guard). Algorithm follows Octave-image's normxcorr2.m.

Parameters
templTemplate image (m × n).
imgSearch image (M × N, must be larger than templ).
mrMemory resource (nullptr → process default).
Returns
Correlation map.

◆ ntsc2rgb()

Value nk::image::ntsc2rgb ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

NTSC YIQ → RGB (inverse of rgb2ntsc).

Parameters
xYIQ image / colormap.
mrMemory resource.
Returns
RGB image / colormap.

◆ ordfilt2()

Value nk::image::ordfilt2 ( const Value & A,
int nth,
const Value & domain,
const Value & S,
PadMode boundary,
double pad_value,
std::pmr::memory_resource * mr = nullptr )

2-D order-statistic filter (B = ordfilt2(A, nth, domain, S)).

For each output pixel the neighbourhood selected by domain (non-zero entries) is gathered, optionally offset by S (same size as domain), sorted, and the nth-order element returned (1-based). boundary controls padding when the neighbourhood crosses the image edge. Output class matches A.

Parameters
AInput image.
nthOrder-statistic index (1-based).
domainNeighbourhood mask.
SOffset matrix, same size as domain.
boundaryPadding mode for off-edge accesses.
pad_valueConstant pad value (if boundary == Constant).
mrMemory resource (nullptr → process default).
Returns
Filtered image, same class as A.
See also
medfilt2

◆ otf2psf()

Value nk::image::otf2psf ( const Value & OTF,
Span< const size_t > outsize = {},
std::pmr::memory_resource * mr = nullptr )

OTF → PSF (PSF = otf2psf(OTF, outsize)).

Inverse of psf2otf: applies the inverse 2-D FFT, then circularly shifts by +floor(size(PSF) / 2) to recover the centred PSF. Output is DOUBLE if the imaginary part is negligible, COMPLEX otherwise.

Parameters
OTFOptical transfer function.
outsizeDesired output size; empty span → no crop.
mrMemory resource (nullptr → process default).
Returns
PSF (DOUBLE or COMPLEX).
See also
psf2otf

◆ otsuthresh()

std::tuple< Value, Value > nk::image::otsuthresh ( const Value & counts,
std::pmr::memory_resource * mr = nullptr )

Otsu's threshold from a precomputed histogram ([level, em] = otsuthresh(counts)).

Parameters
countsHistogram counts (length L vector).
mrMemory resource (nullptr → process default).
Returns
Tuple (level, em) both in [0, 1].
See also
graythresh

◆ padarray()

Value nk::image::padarray ( const Value & x,
const std::vector< int > & padsize,
PadMode mode,
double pad_value,
const std::string & direction,
std::pmr::memory_resource * mr = nullptr )

Pad an array by padsize elements on each side (B = padarray(A, padsize, mode, val, dir)).

padsize is a 1-D vector with one entry per dimension. Direction controls which side(s) to pad:

  • "both" (default): pad both sides.
  • "pre": pad before each dimension.
  • "post": pad after each dimension.
Parameters
xInput array.
padsizePer-dimension pad widths.
modePadMode.
pad_valueConstant value (used iff mode == Constant).
direction"both" / "pre" / "post".
mrMemory resource (nullptr → process default).
Returns
Padded array.

◆ peekTiff()

void nk::image::peekTiff ( const std::string & path,
std::uint32_t & W,
std::uint32_t & H,
std::uint16_t & bits,
std::uint16_t & channels )

Peek a TIFF file's first-IFD metadata without decoding pixels.

Output struct: Width, Height, BitsPerSample, NumberOfChannels.

See also
imfinfo

◆ phantom()

std::tuple< Value, Value > nk::image::phantom ( const Value & model_or_E,
size_t n,
std::pmr::memory_resource * mr = nullptr )

Shepp-Logan computational head phantom ([P, E] = phantom(model_or_E, n)).

Generates the classic CT test image.

Parameters
model_or_EEither a string "Shepp-Logan" / "Modified Shepp-Logan" (default), or an N × 6 matrix of ellipse parameters {I, a, b, x0, y0, phi_deg}.
nOutput size (n × n).
mrMemory resource (nullptr → process default).
Returns
(P, E) — image and ellipse matrix actually used.

◆ pink_cmap()

Value nk::image::pink_cmap ( int n,
std::pmr::memory_resource * mr = nullptr )

Pastel-pink colormap (map = pink(n)).

Piecewise linspace ramps for R/G/B then elementwise sqrt for saturation lift.

Parameters
nRow count.
mrMemory resource.
Returns
n × 3 colormap.

◆ planar2raw()

Value nk::image::planar2raw ( const Value & I,
std::pmr::memory_resource * mr = nullptr )

Re-interleave 4 sensor planes into a full Bayer CFA mosaic (cfa = planar2raw(I)).

Inverse of raw2planar. Takes an (M)×(N)×4 array and produces a (2M)×(2N) mosaic by inverse parity-based copy. Class preserved.

Parameters
IM×N×4 numeric / logical sensor-plane array.
mrMemory resource (nullptr → process default).
Returns
(2M)×(2N) mosaic of the input class.

◆ poly2mask()

Value nk::image::poly2mask ( const Value & X,
const Value & Y,
std::size_t M,
std::size_t N,
std::pmr::memory_resource * mr = nullptr )

Convert polygon to binary mask (BW = poly2mask(X, Y, M, N)).

Scan-converts the polygon (X, Y) into an M × N binary mask using MATLAB R2025b's pixel-centre containment rule (verified empirically against the closed-source images.internal.builtins .poly2mask):

Pixel (r, c) is set in BW iff its centre (c, r) lies in the polygon under even-odd ray-casting with each non-horizontal edge contributing only when \( \text{centre}_y \in (\min(y_1, y_2), \max(y_1, y_2)] \) (half-open below, closed above) and the crossing condition is \( \text{centre}_x > x_\text{intersect} \). This handles vertex sharing and edge coincidence without double-counting.

The polygon is auto-closed (last vertex joined to first) if the caller hasn't already supplied a closing vertex. Empty X / Y returns false(M, N).

References: classic scanline polygon fill (Foley/van Dam et al., Computer Graphics: Principles and Practice, 2nd ed., §3.5); half-open horizontal-edge convention from PostScript / X11 XFillPolygon.

Parameters
XPolygon X coordinates (any real numeric vector).
YPolygon Y coordinates (matching length).
MMask height (rows).
NMask width (cols).
mrMemory resource (nullptr → process default).
Returns
M × N logical mask.

◆ prism_cmap()

Value nk::image::prism_cmap ( int n,
std::pmr::memory_resource * mr = nullptr )

Cyclic 6-row rainbow palette (map = prism(n)).

[red, orange, yellow, green, blue, violet].

Parameters
nRow count.
mrMemory resource.
Returns
n × 3 colormap.

◆ psf2otf()

Value nk::image::psf2otf ( const Value & PSF,
Span< const size_t > outsize = {},
std::pmr::memory_resource * mr = nullptr )

PSF → OTF (OTF = psf2otf(PSF, outsize)).

Pads PSF with zeros to outsize, circularly shifts by \( -\lfloor \text{size}(PSF) / 2 \rfloor \) so the PSF centre lands at the origin, then applies 2-D FFT (or 1-D for vectors).

Parameters
PSFPoint spread function.
outsizeDesired output size; empty span → same as PSF.
mrMemory resource (nullptr → process default).
Returns
COMPLEX OTF.
See also
otf2psf

◆ psnr()

Value nk::image::psnr ( const Value & A,
const Value & B,
double peak,
std::pmr::memory_resource * mr = nullptr )

Peak signal-to-noise ratio (r = psnr(A, B, peak)).

\( \text{PSNR} = 10\log_{10}\!\left(\dfrac{\text{peak}^2}{\text{MSE}(A, B)}\right) \) in dB. peak defaults to the class maximum: 255 for UINT8, 65535 for UINT16, 1.0 for floating point. Pass a positive value to override.

Parameters
AFirst image.
BSecond image (same shape as A).
peakPeak intensity (positive; 0 → class default).
mrMemory resource (nullptr → process default).
Returns
PSNR in dB. Returns +Inf when MSE = 0.
See also
immse, ssim

◆ rangefilt()

Value nk::image::rangefilt ( const Value & I,
const Value & domain,
std::pmr::memory_resource * mr = nullptr )

Local max − min over a neighbourhood (B = rangefilt(I, domain)).

Default domain = true(3). Symmetric boundary. Output type matches input class.

Parameters
IInput image.
domainNeighbourhood mask.
mrMemory resource (nullptr → process default).
Returns
Local range image, same class as I.
See also
stdfilt

◆ raw2planar()

Value nk::image::raw2planar ( const Value & cfa,
std::pmr::memory_resource * mr = nullptr )

Deinterleave a Bayer CFA mosaic into its four sensor planes (P = raw2planar(cfa)).

Splits an M×N mosaic into an (M/2)×(N/2)×4 array where the channels are, in order, the (odd-row, odd-col), (odd-row, even-col), (even-row, odd-col), (even-row, even-col) sub-samples. No interpolation; pure parity-based copy. Class preserved.

Parameters
cfaM×N numeric / logical mosaic. M, N must be even.
mrMemory resource (nullptr → process default).
Returns
(M/2)×(N/2)×4 array of the input class.

◆ readTiff() [1/2]

Value nk::image::readTiff ( const std::string & path,
std::pmr::memory_resource * mr = nullptr )

Minimal TIFF reader for the formats stb doesn't decode.

Implements the baseline uncompressed subset of TIFF 6.0:

  • Compression = 1 (none) only
  • Photometric = 1 (BlackIsZero gray) or 2 (RGB)
  • SamplesPerPixel ∈ {1, 3, 4}; BitsPerSample ∈ {8, 16}
  • PlanarConfiguration = 1 (chunky)
  • Single-page (first IFD)
  • Both byte orders (II little-endian, MM big-endian)

Throws a clear error for any branch outside this set (compression schemes, planar layout, palette / CMYK, multi-page, float / int samples). Future cycles will widen the coverage.

Parameters
pathFilesystem path.
mrMemory resource (nullptr → process default).
Returns
H × W uint8 / uint16 (gray) or H × W × {3, 4} uint8 / uint16.
See also
imread

◆ readTiff() [2/2]

Value nk::image::readTiff ( const std::string & path,
std::uint32_t page,
std::pmr::memory_resource * mr = nullptr )

Multi-page form: read the page-th IFD (1-based).

MATLAB's imread(file, k) semantics.

◆ readTiffWithMap()

std::pair< Value, Value > nk::image::readTiffWithMap ( const std::string & path,
std::uint32_t page,
std::pmr::memory_resource * mr = nullptr )

Two-output read for palette TIFFs: returns (indices, colormap).

indices is the same as readTiff (uint8 / uint16). colormap is K×3 DOUBLE in [0, 1] for palette files (Photometric = 3), or empty for non-palette files. K = 2^BitsPerSample. Matches MATLAB's [A, map] = imread(file) for indexed images.

◆ reducepoly()

Value nk::image::reducepoly ( const Value & P,
double tolerance,
std::pmr::memory_resource * mr = nullptr )

Reduce point density of a polyline / polygon (P_reduced = reducepoly(P, tolerance)).

Ramer-Douglas-Peucker line simplification: recursively split the run of points at the vertex farthest from the chord between the current endpoints; a run is collapsed to its endpoints once no interior vertex deviates from that chord by more than tolerance. tolerance is in [0, 1] and is normalised by the bounding-box diagonal norm(max(P) - min(P)); 0 is treated as eps (minimal reduction), 1 leaves only the endpoints. The first farthest vertex wins on ties.

P is an n × 2 [x y] matrix. Output class equals the input class (integer inputs are computed in single and cast back); the output rows are exact copies of retained input vertices.

Reference: D. Douglas & T. Peucker, Cartographica 10(2):112-122, 1973.

Parameters
Pn × 2 point matrix.
toleranceSensitivity in [0, 1] (default 0.001 in adapter).
mrMemory resource (nullptr → process default).
Returns
m × 2 reduced point matrix, same class as P.
Exceptions
ErrorP not n × 2, or tolerance outside [0, 1].
See also
poly2mask, roipoly, bwboundaries

◆ regionfill()

Value nk::image::regionfill ( const Value & I,
const Value & mask,
std::pmr::memory_resource * mr = nullptr )

Fill image regions via inward Laplacian interpolation (J = regionfill(I, MASK)).

Smoothly inpaints the masked region by solving the discrete Dirichlet boundary value problem \( \nabla^2 J = 0 \) over masked pixels, with the unmasked pixels on the mask perimeter as boundary conditions. Each interior unknown satisfies \( 4 J(r,c) - J_N - J_S - J_W - J_E = 0 \); for pixels on the image border the on-grid neighbour count drops to 3 (edge) or 2 (corner). Solved with conjugate gradient at tol 1e-12 (matrix is sparse SPD; ~sqrt(nMask) iterations).

References: Gonzalez & Woods, Digital Image Processing, §3.4 (Laplacian); Press et al., Numerical Recipes, §2.7 (sparse iterative solvers).

Constraints:

  • I 2-D numeric, ≥ 3 × 3.
  • MASK same size as I, logical or numeric (cast to logical; NaNs are forbidden).
  • Polygon form regionfill(I, X, Y) requires poly2mask (separate function, not yet implemented).

Output class equals input class (cast back from DOUBLE solve).

Parameters
I2-D grayscale image (any real numeric class).
maskLogical mask of pixels to fill.
mrMemory resource (nullptr → process default).
Returns
Filled image, same class and shape as I.

◆ regionprops()

Value nk::image::regionprops ( const Value & BW_or_L,
const std::vector< std::string > & props,
const Value & intensity,
std::pmr::memory_resource * mr = nullptr )

Per-region descriptors (S = regionprops(BW_or_L, props)).

Accepts either a binary image (bwlabel is run internally) or a pre-labelled integer image.

Supported props (case-insensitive):

  • "Area" : pixel count.
  • "Centroid" : 1×2 row [x y] in image coords (1-based).
  • "BoundingBox" : 1×4 row [xmin ymin width height].
  • "all" : all of the above.

Default (empty props): all of the above.

Parameters
BW_or_LBinary or labelled image.
propsProperty names to compute.
mrMemory resource (nullptr → process default).
Returns
Struct array (one element per region).
Parameters
intensityOptional grayscale image for the intensity measurements (MeanIntensity / MaxIntensity / MinIntensity / WeightedCentroid / PixelValues). Pass Value{} (Unset) for none.

◆ rgb2gray()

Value nk::image::rgb2gray ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

Rec.

601 luminance (Y = rgb2gray(X)).

\( Y = 0.2989\,R + 0.5870\,G + 0.1140\,B \). Output class matches input.

Parameters
xInput RGB image.
mrMemory resource (nullptr → process default).
Returns
Grayscale image, same class as x.
See also
im2gray

◆ rgb2hsv()

Value nk::image::rgb2hsv ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

RGB → HSV (hsv = rgb2hsv(rgb)).

Output is DOUBLE: H ∈ [0, 1] (hue normalised), S ∈ [0, 1], V ∈ [0, 1].

Parameters
xInput RGB image / colormap.
mrMemory resource (nullptr → process default).
Returns
HSV image / colormap (DOUBLE).
See also
hsv2rgb

◆ rgb2ind_inmap()

std::pair< Value, Value > nk::image::rgb2ind_inmap ( const Value & RGB,
const Value & cmap,
std::pmr::memory_resource * mr = nullptr )

RGB → indexed image with a fixed colormap ([ind, cmap] = rgb2ind(RGB, cmap)).

Nearest-neighbour quantisation (squared Euclidean in normalised RGB). Output index is UINT8 if cmap has ≤ 256 rows, else UINT16. KNOWN GAP: scalar-Q (min-variance) and scalar-tol (uniform) forms deferred.

Parameters
RGBSource image.
cmapK × 3 colormap.
mrMemory resource (nullptr → process default).
Returns
(ind, cmap) pair.

◆ rgb2lab()

Value nk::image::rgb2lab ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

sRGB → CIE L*a*b* (D65) (lab = rgb2lab(rgb)).

Internally routes through rgb2xyz → xyz2lab. Output is DOUBLE Lab in the canonical scale: L* ∈ [0, 100], a*, b* ∈ [-128, 127] roughly.

Parameters
xsRGB image / colormap.
mrMemory resource (nullptr → process default).
Returns
Lab image / colormap.
See also
lab2rgb, rgb2lightness

◆ rgb2lightness()

Value nk::image::rgb2lightness ( const Value & RGB,
std::pmr::memory_resource * mr = nullptr )

Lightness L* (L = rgb2lightness(RGB)).

Returns an H × W SINGLE image. Equivalent to the first plane of rgb2lab.

Parameters
RGBsRGB image.
mrMemory resource (nullptr → process default).
Returns
Lightness image.

◆ rgb2lin()

Value nk::image::rgb2lin ( const Value & A,
std::pmr::memory_resource * mr = nullptr )

sRGB → linear RGB gamma inverse (B = rgb2lin(A)).

Per-element piecewise: |x| < 0.04045 → x / 12.92; otherwise sign(x) · ((|x| + 0.055) / 1.055)^2.4. Negatives are mirrored through the gamma curve. Output class is DOUBLE if input is DOUBLE, else SINGLE. Only "sRGB" colourspace supported.

Parameters
AInput image / colormap.
mrMemory resource (nullptr → process default).
Returns
Linearised image / colormap.
See also
lin2rgb

◆ rgb2ntsc()

Value nk::image::rgb2ntsc ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

RGB → NTSC YIQ (yiq = rgb2ntsc(rgb)).

Y ∈ [0, 1], I and Q ∈ [-1, 1] approximately.

Parameters
xRGB image / colormap.
mrMemory resource (nullptr → process default).
Returns
YIQ image / colormap.
See also
ntsc2rgb

◆ rgb2xyz()

Value nk::image::rgb2xyz ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

sRGB → CIE XYZ (D65) (xyz = rgb2xyz(rgb)).

Applies sRGB linearisation then the standard 3×3 matrix transform.

Parameters
xsRGB image / colormap.
mrMemory resource (nullptr → process default).
Returns
XYZ image / colormap (DOUBLE).
See also
xyz2rgb, rgb2lin

◆ rgb2ycbcr()

Value nk::image::rgb2ycbcr ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

RGB → YCbCr (BT.601) (ycbcr = rgb2ycbcr(rgb)).

Parameters
xRGB image / colormap.
mrMemory resource (nullptr → process default).
Returns
YCbCr image / colormap (DOUBLE).
See also
ycbcr2rgb

◆ rgbwide2xyz()

Value nk::image::rgbwide2xyz ( const Value & RGB,
int bits_per_sample,
const std::string & color_space,
const std::string & linearization,
std::pmr::memory_resource * mr = nullptr )

Narrow-range wide-gamut RGB → CIE 1931 XYZ (XYZ = rgbwide2xyz(RGB, BPS, ...)).

Decodes BT.2020 or BT.2100 RGB values to CIE 1931 XYZ tristimulus values. Pipeline:

  1. Remove black-level offset and scale to nominal [0, 1]: lin = (raw - blackLevel) / (nominalPeak - blackLevel).
  2. Inverse transfer function:
    • BT.2020 (default), 10-bit: α = 1.099, β = 0.018.
    • BT.2020, 12-bit: α = 1.0993, β = 0.0181.
    • BT.2100 PQ: α = 1.099, β = 0.018 (hardcoded — MATLAB's "PQ" path actually applies the BT.2020-style transfer with fixed α/β regardless of bit depth, NOT the SMPTE ST 2084 PQ curve).
    • BT.2100 HLG: piecewise (v² / 3) below 1/2, (exp((v-c)/a) + b) / 12 above. Constants a = 0.17883277, b = 1 - 4a, c = 0.5 - a·ln(4a).
  3. Matrix transform RGB → XYZ via BT.2020 primaries (D65): M = [0.636958 0.144617 0.168881; 0.262700 0.677998 0.059302; 0.000000 0.028073 1.060985] (xr=0.708/yr=0.292, xg=0.170/yg=0.797, xb=0.131/yb=0.046 with D65).
  4. Optional Bradford chromatic adaptation if whitepoint ≠ D65.

Bit depths supported: 10, 12.

References:

  • ITU-R Rec. BT.2020-2 (10/2015).
  • ITU-R Rec. BT.2100-2 (07/2018).
Parameters
RGBNarrow-range uint16 values (10-bit: [64,940]; 12-bit: [256,3760]). Shape H × W × 3 or N × 3.
bits_per_sample10 or 12.
color_space"BT.2020" (def) / "BT.2100".
linearization"PQ" (def) / "HLG" — BT.2100 only.
mrMemory resource.
Returns
DOUBLE XYZ values.

◆ rgbwide2ycbcr()

Value nk::image::rgbwide2ycbcr ( const Value & RGB,
int bits_per_sample,
std::pmr::memory_resource * mr = nullptr )

BT.2020 / BT.2100 wide-gamut RGB → YCbCr (ycbcr = rgbwide2ycbcr(RGB, bps)).

Non-constant-luminance YCbCr per ITU-R BT.2020-2 / BT.2100-2 (10-bit or 12-bit narrow-range). bps must be 10 or 12. Input RGB is UINT16 with values in [64, 940] (10-bit) or [256, 3760] (12-bit); out-of-range pixels are mapped via the same affine transform but the result is no longer guaranteed to land in the nominal YCbCr range.

Algorithm:

  • Normalise: rgbN = (RGB − blackLevel) / nominalRange
  • Y' = 0.2627·R + 0.6780·G + 0.0593·B
  • Cb = (B − Y')/1.8814, Cr = (R − Y')/1.4746
  • Quantise: Y_out = uint16((219·Y' + 16 )·2^(bps−8)), Cb_out = uint16((224·Cb + 128)·2^(bps−8)), Cr_out = uint16((224·Cr + 128)·2^(bps−8))

Accepts p × 3 colour lists (returned as p × 3) and H × W × 3 images.

Parameters
RGBUINT16 wide-gamut RGB.
bits_per_sample10 or 12.
mrMemory resource (nullptr → process default).
Returns
UINT16 YCbCr, same shape as RGB.

◆ roicolor()

Value nk::image::roicolor ( const Value & A,
const Value & low_or_v,
double high,
bool is_range,
std::pmr::memory_resource * mr = nullptr )

Region-of-interest mask (BW = roicolor(A, low, high)).

Two forms (selected by is_range):

  • Range form: BW = (A >= low) & (A <= high) — inclusive.
  • Set form (is_range = false): BW(i) = any(A(i) == v) where v = low_or_v is treated as a vector.
Parameters
AInput image.
low_or_vRange low / value vector.
highRange high (ignored in set form).
is_rangetrue → range form, false → set form.
mrMemory resource (nullptr → process default).
Returns
Logical mask same shape as A.

◆ roifilt2()

Value nk::image::roifilt2 ( const Value & h,
const Value & I,
const Value & BW,
std::pmr::memory_resource * mr = nullptr )

Filter a region of interest (J = roifilt2(h, I, BW)).

Filters the grayscale image I with the 2-D linear filter h (imfilter defaults: correlation, zero boundary, same size) and returns I with only the masked (BW) pixels replaced by the filtered values. The output equals I outside the mask. Output class equals class(I).

The function-handle form J = roifilt2(I, BW, fun) — apply fun to I, then keep only the masked pixels (output class follows fun's result) — is handled by the registration adapter, which needs the engine to invoke the handle.

Parameters
h2-D linear filter kernel.
IGrayscale 2-D image.
BWMask (logical or numeric, BW != 0), same size as I.
mrMemory resource (nullptr → process default).
Returns
Filtered image, same size and class as I.
Exceptions
ErrorI not 2-D, or BW size mismatch.
See also
imfilter, filter2, roipoly

◆ roipoly()

Value nk::image::roipoly ( double xdata_lo,
double xdata_hi,
double ydata_lo,
double ydata_hi,
std::size_t M,
std::size_t N,
const Value & xi,
const Value & yi,
std::pmr::memory_resource * mr = nullptr )

Polygonal region-of-interest mask (BW = roipoly(A, xi, yi), world-coord variants).

Programmatic (non-interactive) implementation of MATLAB R2025b's roipoly. Auto-closes the polygon, maps (xi, yi) from world to pixel coordinates via axes2pix using the image extents [xdata_lo, xdata_hi] × [ydata_lo, ydata_hi], then scan- converts via poly2mask.

Argument forms (handled by the engine adapter; this typed entry-point takes the fully-expanded set):

  • roipoly(A, xi, yi) — image-based, world extents default to [1 size(A,2)] × [1 size(A,1)].
  • roipoly(M, N, xi, yi) — size-based, default extents.
  • roipoly(x, y, A, xi, yi) — world extents from x, y.
  • roipoly(x, y, M, N, xi, yi) — world extents and explicit size.

Interactive forms (roipoly(), roipoly(A), roipoly(M,N)) throw — they require a figure / mouse and have no headless semantics.

Parameters
xdata_loImage extent low along x (typically 1).
xdata_hiImage extent high along x (typically N).
ydata_loImage extent low along y (typically 1).
ydata_hiImage extent high along y (typically M).
MMask height.
NMask width.
xiPolygon X coordinates (world units).
yiPolygon Y coordinates (world units).
mrMemory resource (nullptr → process default).
Returns
M × N logical mask.

◆ spring_cmap()

Value nk::image::spring_cmap ( int n,
std::pmr::memory_resource * mr = nullptr )

Magenta → yellow colormap (map = spring(n)).

r = 1, g = (0:n-1)/(n-1), b = 1 - g.

Parameters
nRow count.
mrMemory resource.
Returns
n × 3 colormap.

◆ ssim()

Value nk::image::ssim ( const Value & A,
const Value & B,
std::pmr::memory_resource * mr = nullptr )

Structural similarity index (r = ssim(A, B)).

Wang-Bovik SSIM with a fixed 11 × 11 Gaussian window (σ = 1.5) and constants K1 = 0.01, K2 = 0.03. Output is a real scalar in roughly [-1, 1] (1 = identical).

Parameters
AFirst image.
BSecond image (same shape).
mrMemory resource (nullptr → process default).
Returns
SSIM scalar.
See also
immse, psnr

◆ std2()

Value nk::image::std2 ( const Value & A,
std::pmr::memory_resource * mr = nullptr )

Standard deviation of every element (s = std2(A)).

Normalised by N - 1 (sample standard deviation).

Parameters
AInput image.
mrMemory resource (nullptr → process default).
Returns
Scalar standard deviation.
See also
mean2

◆ stdfilt()

Value nk::image::stdfilt ( const Value & I,
const Value & domain,
std::pmr::memory_resource * mr = nullptr )

Local sample standard deviation (B = stdfilt(I, domain)).

Standard deviation of the neighbourhood defined by domain (logical / numeric mask; non-zero entries select neighbours). Default domain = ones(3). Boundary = symmetric. Output is double.

Parameters
IInput image.
domainNeighbourhood mask (logical / numeric).
mrMemory resource (nullptr → process default).
Returns
DOUBLE matrix of local std-devs, same shape as I.
See also
rangefilt, entropyfilt

◆ strel()

Value nk::image::strel ( const std::string & shape,
const std::vector< double > & params,
const Value & arbitrary_nhood,
std::pmr::memory_resource * mr = nullptr )

Build a 2-D structuring element (SE = strel(shape, params, arbitrary_nhood)).

Supported shapes:

  • "square" — N×N square; params = [N].
  • "rectangle" — params = [m, n].
  • "diamond" — params = [r] (radius).
  • "disk" — params = [r] (decomposed approximation).
  • "line" — params = [L, theta_deg].
  • "arbitrary" / "" — caller-provided mask in arbitrary_nhood.
Parameters
shapeShape name (see table).
paramsNumeric shape parameters.
arbitrary_nhoodMask for "arbitrary" (empty otherwise).
mrMemory resource (nullptr → process default).
Returns
LOGICAL matrix (1 = neighbourhood pixel).
Exceptions
ErrorUnknown shape (m:strel:badShape).
See also
imerode, imdilate

◆ stretchlim()

Value nk::image::stretchlim ( const Value & I,
double low_tol,
double high_tol,
std::pmr::memory_resource * mr = nullptr )

Stretch limits from saturation tolerances (lim = stretchlim(I, [low_tol, high_tol])).

Returns a 2-element column with the low / high intensities chosen so low_tol fraction of pixels fall below the lower limit and 1 − high_tol fraction above the upper limit. Default low_tol = 0.01, high_tol = 0.99. Computed per channel for RGB.

Parameters
IInput image.
low_tolLower-tail fraction in [0, 1].
high_tolUpper-tail cutoff in [0, 1].
mrMemory resource (nullptr → process default).
Returns
2-element column [low, high] (or 2×3 for RGB).
See also
imadjust

◆ summer_cmap()

Value nk::image::summer_cmap ( int n,
std::pmr::memory_resource * mr = nullptr )

Green → yellow colormap (map = summer(n)).

r = (0:n-1)/(n-1), g = 0.5 + r/2, b = 0.4.

Parameters
nRow count.
mrMemory resource.
Returns
n × 3 colormap.

◆ tiffNumPages()

std::uint32_t nk::image::tiffNumPages ( const std::string & path)

Count the number of IFDs (pages) in a TIFF file.

Walks the IFD chain without decoding any pixel data.

◆ tonemap()

Value nk::image::tonemap ( const Value & HDR,
double lremap_lo,
double lremap_hi,
double saturation,
int ntilesR,
int ntilesC,
std::pmr::memory_resource * mr = nullptr )

Render high-dynamic-range image for low-dynamic-range display (RGB = tonemap(HDR, ...)).

Ward's log-luminance equalisation followed by adaptive histogram equalisation + lightness/saturation remap. Output is always UINT8.

Pipeline (MATLAB R2025b tonemap.m):

  1. Replace zeros with the global non-zero minimum.
  2. RGBlog2 = log2(HDR); RGBlog2Scaled = mat2gray(RGBlog2).
  3. Grayscale path: adapthisteq(NumTiles=ntiles) → imadjust(LRemap, [0 1]). RGB path: rgb2lab → L/100 → adapthisteq → imadjust → ·100; a/b channels multiplied by saturation; lab2rgb.
  4. im2uint8(result).

References: G. Ward et al., "A Visibility Matching Tone Reproduction Operator for High Dynamic Range Scenes", IEEE TVCG 3(4), 1997.

Parameters
HDR2-D grayscale or H×W×3 single/double HDR image (nonnegative).
lremap_loAdjustLightness low (∈ [0, 1]). Default 0.
lremap_hiAdjustLightness high (∈ [0, 1]). Default 1.
saturationAdjustSaturation (≥ 0). Default 1.
ntilesRNumberOfTiles rows (default 4).
ntilesCNumberOfTiles cols (default 4).
mrMemory resource (nullptr → process default).
Returns
UINT8 LDR image, same H×W×{1,3} as HDR.

◆ wavelength2rgb()

Value nk::image::wavelength2rgb ( const Value & wavelength,
const std::string & out_class,
double gamma,
std::pmr::memory_resource * mr = nullptr )

Wavelength → RGB (Bruton 1996) (RGB = wavelength2rgb(wavelength, class, gamma)).

Piecewise visible-light mapping. Scalar input → 1 × 3; vector → 1 × N × 3 / N × 1 × 3; matrix → H × W × 3.

Parameters
wavelengthWavelength(s) in nanometres.
out_classOutput class (default "double").
gammaGamma correction (default 0.8).
mrMemory resource (nullptr → process default).
Returns
RGB image / colormap of the requested class.

◆ wcodemat()

Value nk::image::wcodemat ( const Value & X,
int nb,
const std::string & opt,
int absol,
std::pmr::memory_resource * mr = nullptr )

Wavelet-display quantisation (Y = wcodemat(X, nb, opt, absol)).

Quantises and scales X into integer codes in [1, nb]. Output is DOUBLE; a canonical wavelet-display helper.

Parameters
XInput coefficient matrix.
nbCode range upper bound.
opt"mat" (default, global), "row", or "col".
absol1 → use abs(X) (default), 0 → use X.
mrMemory resource (nullptr → process default).
Returns
DOUBLE matrix of integer codes in [1, nb].

◆ white_cmap()

Value nk::image::white_cmap ( int n,
std::pmr::memory_resource * mr = nullptr )

All-ones colormap (map = white(n)).

Parameters
nRow count.
mrMemory resource.
Returns
n × 3 all-ones colormap.

◆ whitepoint()

Value nk::image::whitepoint ( const std::string & illuminant,
std::pmr::memory_resource * mr = nullptr )

CIE reference-illuminant tristimulus (wp = whitepoint(illuminant)).

Supported (case-insensitive): "a" (Tungsten 2856 K), "c" (Average daylight), "d50" (Horizon), "d55", "d65" (Noon), "e" (Equal-energy), "icc" (default, ICC profile D50).

Parameters
illuminantIlluminant code.
mrMemory resource (nullptr → process default).
Returns
1 × 3 XYZ tristimulus.
Exceptions
ErrorUnknown illuminant code.

◆ wiener2()

std::tuple< Value, Value > nk::image::wiener2 ( const Value & I,
size_t nh,
size_t nw,
double noise,
std::pmr::memory_resource * mr = nullptr )

Adaptive Wiener noise reduction ([J, noise] = wiener2(I, nh, nw, noise)).

Lim 1989 eqs. 9.26-9.29. Local mean μ and variance σ² in an nh × nw box neighbourhood (default 3×3, zero-pad boundary). When noise is NaN it is estimated as the mean of σ² across the image. Returns (denoised, noise) where denoised is cast back to the input class.

Parameters
IInput image.
nhNeighbourhood rows.
nwNeighbourhood cols.
noiseNoise power estimate (NaN → measure from I).
mrMemory resource (nullptr → process default).
Returns
Tuple (denoised, noise).

◆ winter_cmap()

Value nk::image::winter_cmap ( int n,
std::pmr::memory_resource * mr = nullptr )

Blue → cyan-ish colormap (map = winter(n)).

r = 0, g = (0:n-1)/(n-1), b = 1 - g/2.

Parameters
nRow count.
mrMemory resource.
Returns
n × 3 colormap.

◆ writeTiff()

void nk::image::writeTiff ( const Value & A,
const std::string & path,
const std::string & compression = "none",
bool appendMode = false )

Write A to path as a baseline TIFF.

Companion to readTiff().

Supports uint8 / uint16 inputs (other numeric types are clamped to uint8). Channels: 1 (gray), 3 (RGB), 4 (RGBA). Compression options: "none", "packbits", "lzw", "deflate" (Deflate requires NK_WITH_ZLIB at build time).

Parameters
AImage (uint8 / uint16; 1, 3, or 4 channels).
pathOutput path.
compressionCompression scheme name.
appendModeIf true and the file already exists, append a new IFD; otherwise overwrite.

◆ writeTiffToBytes()

std::vector< std::uint8_t > nk::image::writeTiffToBytes ( const Value & A,
const std::string & compression = "none",
const std::vector< std::uint8_t > * existing = nullptr )

Buffer form — encode A to a TIFF byte vector (the engine entry writes these through the VFS).

When existing is non-null and non-empty, a new IFD is appended to those bytes (multi-page); otherwise a fresh single-page file is produced.

Parameters
AImage (uint8 / uint16; 1, 3, or 4 channels).
compression"none" | "packbits" | "lzw" | "deflate".
existingOptional bytes of a prior TIFF to append a page to.

◆ xyz2double()

Value nk::image::xyz2double ( const Value & xyz,
std::pmr::memory_resource * mr = nullptr )

XYZ → DOUBLE (xyzd = xyz2double(xyz)).

Follows the ICC.1:2001-4 convention: UINT16 32768 → 1.0. DOUBLE input passes through. Shape preserved.

Parameters
xyzInput XYZ image / colormap (DOUBLE or UINT16).
mrMemory resource (nullptr → process default).
Returns
DOUBLE XYZ.
See also
xyz2uint16

◆ xyz2lab()

Value nk::image::xyz2lab ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

CIE XYZ → CIE L*a*b* (D50 ICC reference white).

Parameters
xXYZ image / colormap.
mrMemory resource.
Returns
Lab image / colormap.
See also
lab2xyz, rgb2lab

◆ xyz2rgb()

Value nk::image::xyz2rgb ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

CIE XYZ → sRGB (inverse of rgb2xyz).

Parameters
xXYZ image / colormap.
mrMemory resource.
Returns
sRGB image / colormap (DOUBLE).

◆ xyz2rgbwide()

Value nk::image::xyz2rgbwide ( const Value & XYZ,
int bits_per_sample,
const std::string & color_space,
const std::string & linearization,
std::pmr::memory_resource * mr = nullptr )

CIE 1931 XYZ → narrow-range wide-gamut RGB (RGB = xyz2rgbwide(XYZ, BPS, ...)).

Inverse of rgbwide2xyz. Same color-space and transfer-function options. Returns uint16 narrow-range values clipped to the nominal peak / black levels.

Parameters
XYZDOUBLE XYZ values, shape H × W × 3 or N × 3.
bits_per_sample10 or 12.
color_space"BT.2020" (def) / "BT.2100".
linearization"PQ" (def) / "HLG" — BT.2100 only.
mrMemory resource.
Returns
UINT16 narrow-range RGB.

◆ xyz2uint16()

Value nk::image::xyz2uint16 ( const Value & xyz,
std::pmr::memory_resource * mr = nullptr )

XYZ → UINT16 ICC encoding (xyzu16 = xyz2uint16(xyz)).

Inverse of xyz2double: uint16 = saturate(round(double · 32768)). Negative values clip to 0; values >= 65535/32768 ≈ 1.99997 saturate to 65535. UINT16 input passes through.

Parameters
xyzInput XYZ image / colormap.
mrMemory resource (nullptr → process default).
Returns
UINT16 XYZ.

◆ ycbcr2rgb()

Value nk::image::ycbcr2rgb ( const Value & x,
std::pmr::memory_resource * mr = nullptr )

YCbCr → RGB (inverse of rgb2ycbcr).

Parameters
xYCbCr image / colormap.
mrMemory resource.
Returns
RGB image / colormap (DOUBLE).

◆ ycbcr2rgbwide()

Value nk::image::ycbcr2rgbwide ( const Value & YCBCR,
int bits_per_sample,
std::pmr::memory_resource * mr = nullptr )

BT.2020 / BT.2100 wide-gamut YCbCr → RGB (rgb = ycbcr2rgbwide(YCBCR, bps)).

Inverse of rgbwide2ycbcr. Decodes non-constant-luminance YCbCr per ITU-R BT.2020-2 / BT.2100-2 narrow-range. bps must be 10 or 12. Input is UINT16 in the YCbCr nominal ranges:

  • Y ∈ [64, 940] (10-bit) or [256, 3760] (12-bit)
  • Cb, Cr ∈ [64, 960] (10-bit) or [256, 3840] (12-bit)

Algorithm (matches MATLAB R2025b ycbcr2rgbwideImpl.m):

  • Normalise: Y_n = (Y − yzero )/yrange Cb_n = (Cb − chromazero)/chromarange Cr_n = (Cr − chromazero)/chromarange where yzero = 64/256, chromazero = 2^(bps − 1), yrange = peak − zero, chromarange = (peak_chroma) − zero.
  • R = 1.4746·Cr_n + Y_n, B = 1.8814·Cb_n + Y_n G = (Y_n − 0.2627·R − 0.0593·B) / 0.6780
  • Quantise: RGB_out = uint16(rgb·nominalRange + blackLevel) where blackLevel = 64/256, nominalRange = peak − black.

Accepts p × 3 colour lists and H × W × 3 images. Bit-equal MATLAB round-trip with rgbwide2ycbcr.

Parameters
YCBCRUINT16 YCbCr per BT.2020 narrow-range.
bits_per_sample10 or 12.
mrMemory resource (nullptr → process default).
Returns
UINT16 RGB, same shape as YCBCR.