| Table of Contents ▸ Mathematical Expressions | ◀ Substitution Rules | Adding Custom Commands ▶ |
Mathematical Expressions
G'MIC has an embedded mathematical parser, used to evaluate (possibly complex) mathematical expressions specified inside braces {}, or formulas in commands that may take one as an argument (e.g. fill or eval).
When the context allows it, a formula is evaluated for each pixel of the selected images (e.g. fill or eval).
A mathematical expression may return, or take as arguments, either a scalar or a fixed-size vector.
The mathematical parser supports the following operators, functions and variables:Common mathematical operators:
|| (logical or), && (logical and), | (bitwise or), & (bitwise and), !=, ==, <=, >=, <, >, << (left bitwise shift), >> (right bitwise shift), -, +, *, /, % (modulo), ^ (power), ! (logical not), ~ (bitwise not), ++, --, +=, -=, *=, /=, %=, &=, |=, ^=, >>, <<= (in-place operators).Common mathematical functions:
abs(), acos(), acosh(), arg0(), arg1(), argkth(), argmax(), argmaxabs(), argmin(), argminabs(), asin(), asinh(), atan(), atan2(), atanh(), avg(), bool(), cbrt(), ceil(), cos(), cosh(), cut(), deg2rad(), erf(), erfinv(), exp(), fact(), fibo(), floor(), frac(), gamma(), gauss(), gcd(), hypot(), int(), isconst(), isfinite(), isnan(), isnum(), isinf(), isint(), isbool(), isexpr(), isfile(), isdir(), isin(), kth(), lcm(), log(), log2(), log10(), logit(), max(), maxabs(), med(), min(), minabs(), narg(), prod(), rad2deg(), rol() (left bit rotation), ror() (right bit rotation), round(), sign(), sigmoid(), sin(), sinc(), sinh(), sqrt(), std(), srand(_seed), sum(), tan(), tanh(), var(), xor().cov(A,B,_avgA,_avgB) estimates the covariance between vectors A and B (estimated averages of these vectors may be specified as arguments).
mse(A,B) returns the mean-squared error between vectors A and B.
atan2(y,x) is the version of atan() with two arguments y and x (as in C/C++).
perm(k,n,_with_order) computes the number of permutations of k objects from a set of n objects.
gauss(x,_sigma,_is_normalized) returns exp(-x^2/(2*s^2))/(is_normalized?sqrt(2*pi*sigma^2):1).
cut(x,min,_max) returns x if it is in range [min,max], or min or max otherwise.
abscut(x,min,_max,_offset) returns cut(abs(x) + offset,min,max)*sign(x).
narg(a_1,...,a_N) returns the number of given arguments (here, N).
arg0(i,a_0,..,a_N) returns the i-th argument a_i (where index i goes from 0 to N).
arg1(i,a_1,..,a_N) does the same, but for index i going from 1 to N.
indexof(ref,a_0,..,a_N) returns the index i of the element ref in the list of elements a_k (or -1 if ref is not present in the list). Index i starts from 0.
isnum(), isnan(), isinf(), isint(), isbool() test the type of the given number or expression, and return 0 (false) or 1 (true).
isfile('path') (resp. isdir('path)) returns '0 (false) or 1 (true) depending on whether its string argument is a path to an existing file (resp. to a directory).
ispercentage(arg) returns 1 (true) if arg ends with a %, and 0 (false) otherwise.
isvarname('str') returns 0 (false) or 1 (true) depending on whether its string argument is a valid variable name.
isvar(varname) returns 0 (false) or 1 (true) depending on whether varname is an already-defined variable.
isin(v,a_1,...,a_n) returns 0 (false) or 1 (true) depending on whether the first argument v appears in the set of other argument a_i.
isint(x,_xmin,_xmax) returns 1 (true), if x is an integer in range [xmin,xmax], otherwise 0 (false).
inrange(value,m,M,include_m,include_M) returns 0 (false) or 1 (true) depending on whether the given value lies in range [m,M] (include_m and includeM tells how boundaries m and M are considered).
argkth(), argmin(), argmax(), argminabs(), argmaxabs(), avg(), kth(), min(), max(), minabs(), maxabs(), med(), prod(), std(), sum() and var() can be called with an arbitrary number of scalar/vector arguments.
vargkth(), vargmin(), vargmax(), vargminabs(), vargmaxabs(), vavg(), vkth(), vmin(), vmax(), vminabs(), vmaxabs(), vmed(), vprod(), vstd(), vsum() and vvar() are the versions of the previous function with vector arguments.
wave(x,type) defines a periodic function, period 1, with values in [-1,1]. type sets the waveform. It can be { 0:Square | 1:Triangle | 2:Ascending sawtooth | 3:Descending sawtooth | 4:Sine }.
round(value,rounding_value,direction) returns a rounded value. direction can be { -1:To-lowest | 0:To-nearest | 1:To-highest }.
softmax(V,_temperature) and softmin(V,_temperature) respectively returns the softmax and softmin of vector V. Default value for temperature is 1.
softargmax(V,_temperature) and softargmin(V,_temperature) respectively returns the softargmax and softargmin of vector V. Default value for temperature is 1.
lerp(a,b,t) returns a*(1-t)+b*t.
swap(a,b) swaps the values of the given arguments. swap(#ind,offset0,offset1,_is_vector) swaps pixels of image [ind], located at offsets offset0 and offset1.
Predefined variable names:
Variable names below are predefined. They can be overridden though.l: length of the current list of images.
k: index of the current image, in [0,l-1].
w: width of the current image, if any (0 otherwise).
h: height of the current image, if any (0 otherwise).
d: depth of the current image, if any (0 otherwise).
s: spectrum of the current image, if any (0 otherwise).
r: shared state of the current image, if any (0 otherwise).
wh: shortcut for width*height.
whd: shortcut for width*height*depth.
whds: shortcut for width*height*depth*spectrum (i.e. number of image values).
ia, ic, id, im, iM, in, ip, is, iv: Respectively the average, median, standard deviation, minimum, maximum, L2-norm, product, sum and variance of the current image, if any (0 otherwise).
xm, ym, zm, cm: The pixel coordinates of the minimum value in the current image, if any (0 otherwise).
xM, yM, zM, cM: The pixel coordinates of the maximum value in the current image, if any (0 otherwise).
All these variables are considered as constant values by the math parser (for optimization purposes) which is indeed the case most of the time. Anyway, this might not be the case, if function resize(#ind,..) is used in the math expression. If so, it is safer to invoke functions l(), w(_#ind), h(_#ind), ... s(_#ind) and in(_#ind) instead of the corresponding named variables.
i: currently processed pixel value (i.e. value located at (x,y,z,c)) in the current image, if any (0 otherwise).
iN: N-th channel value of currently processed pixel (i.e. value located at (x,y,z,N) in the current image, if any (0 otherwise). N must be an integer in range [0,9].
R, G, B and A are equivalent to i0, i1, i2 and i3 respectively.
I: currently processed vector pixel in the current image, if any (0 otherwise). The number of vector components is equal to the number of image channels (e.g. I = [ R,G,B ] for a RGB image).
_0 and _1: Vectors whose dimension is equal to the number of channels of the current image, and whose values are all 0 or 1.
You may add #ind to any of the variable name above to retrieve the information for any numbered image [ind] in the list (when this makes sense). For instance ia#0 denotes the average value of the first image in the list).
x: currently processed column of the image, if any (0 otherwise).
y: currently processed row of the image, if any (0 otherwise).
z: currently processed slice of the image, if any (0 otherwise).
c: currently processed channel of the image, if any (0 otherwise).
t: thread id when an expression is evaluated with multiple threads (0 means master thread).
n: maximum number of threads when expression is evaluated in parallel (so that t goes from 0 to n-1).
e: value of e, i.e. 2.71828....
pi: value of pi, i.e. 3.1415926....
eps: value of machine epsilon, that is the difference between 1.0 and the next value representable by a double.
u: a random value between [0,1], following a uniform distribution.
v: a random integer that is either 0 or 1, following a uniform distribution.
g: a random value, following a gaussian distribution of variance 1 (roughly in [-6,6]).
interpolation: value of the default interpolation mode used when reading pixel values with the pixel access operators (i.e. when the interpolation argument is not explicitly specified, see below for more details on pixel access operators). Its initial default value is 0.
boundary: value of the default boundary conditions used when reading pixel values with the pixel access operators (i.e. when the boundary condition argument is not explicitly specified, see below for more details on pixel access operators). Its initial default value is 0.
The last image in the list is always associated to the evaluations of expressions, e.g. G'MIC sequence
256,128 fill {w}
will create a 256x128 image filled with value 256.Vector functions and operators:
The math evaluator is able to work with vector elements. A math function applied to a vector argument usually returns a vector with same dimension, where each element of the input vector has been passed to the specified function (e.g. abs([-1,2,-3]) returns [1,2,3]).There are specific functions and operators to define or compute vector elements though :
[a0,a1,...,aN-1] defines a N-dimensional vector with scalar coefficients ak.
vectorN(a0,a1,,...,aN-1) does the same, with the ak being repeated periodically if only a few are specified.
vector(#N,a0,a1,,...,aN-1) does the same, and can be used for any constant expression N.
In previous expressions, the ak can be vectors themselves, to be concatenated into a single vector.
The scalar element ak of a vector X is retrieved by X[k].
The sub-vector [X[p],X[p+s]...X[p+s*(q-1)]] (of size q) of a vector X is retrieved by X[p,q,s].
Equality/inequality comparisons between two vectors is done with operators == and !=.
Some vector-specific functions can be used on vector values: cross(X,Y) (cross product), dot(X,Y) (dot product), size(X) (vector dimension), sort(X,_is_increasing,_starting_index,_nb_elts,_size_elt,_sort_index) (sorted values), reverse(A) (reverse order of components), map(X,P,_nb_channelsX,_nb_channelsP,_boundary_conditions), shift(A,_length,_boundary_conditions) and same(A,B,_nb_vals,_is_case_sensitive) (vector equality test).
Function normP(u1,...,un) computes the LP-norm of the specified vector (P being a constant or inf, as in e.g. norm1()).
Function normp(V,_p) computes the Lp-norm of the vector V. Here, p can be variable. Default value for p is 2.
Function unitnorm(V,_p) returns a normalized version V/normp(V) of vector V. Default value for p is 2.
Function resize(A,size,_interpolation,_boundary_conditions) returns a resized version of a vector A with given interpolation mode. interpolation can be { -1:None (memory content) | 0:None | 1:Nearest | 2:Average | 3:Linear | 4:Grid | 5:Bicubic | 6:Lanczos }, and boundary_conditions can be { 0:Dirichlet | 1:Neumann | 2:Periodic | 3:Mirror }.
Function find(A,B,_starting_index,_search_step) returns the index where sub-vector B appears in vector A, (or -1 if B is not contained in A). Argument A can be also replaced by an image index #ind.
Specifying a vector-valued math expression as an argument of a command that operates on image values (e.g. fill) modifies the whole spectrum range of the processed image(s), for each spatial coordinates (x,y,z). The command does not loop over the c-axis in this case.
Complex-valued functions:
A 2-dimensional vector may be interpreted as a complex number and used in those particular functions/operators: ** (complex multiplication), // (complex division), ^^ (complex exponentiation), **= (complex self-multiplication), //= (complex self-division), ^^= (complex self-exponentiation), cabs() (complex modulus), carg() (complex argument), cconj() (complex conjugate), cexp() (complex exponential), clog() (complex logarithm), ccos() (complex cosine), csin() (complex sine), csqr() (complex square), csqrt() (complex square root), ctan() (complex tangent), ccosh() (complex hyperpolic cosine), csinh() (complex hyperbolic sine) and ctanh() (complex hyperbolic tangent).Matrix-valued functions:
A MN-dimensional vector may be interpreted as a M x N matrix and used in those particular functions/operators: * (matrix-vector multiplication), det(A) (determinant), diag(V) (diagonal matrix from a vector), eig(A) (eigenvalues/eigenvectors), eye(n) (n x n identity matrix), invert(A,_nb_colsA) (matrix inverse), mul(A,B,_nb_colsB) (matrix-matrix multiplication), qr(A,_nb_colsA,_is_reduced_form), rot(u,v,w,angle) (3D rotation matrix), rot(angle) (2D rotation matrix), solve(A,B,_nb_colsB) (solver of linear system A.X = B), svd(A,_nb_colsA) (singular value decomposition), trace(A) (matrix trace) and transpose(A,nb_colsA) (matrix transpose). Argument nb_colsB may be omitted if it is equal to 1.Image-valued functions:
Some functions take vector-valued arguments that represent image data :Function expr(formula,_w,_h,_d,_s,_A) outputs a vector of size w*h*d*s with values generated from the given formula, as if one were filling an image with dimensions (w,h,d,s). If A is specified, it must be a vector of size w*h*d*N (N can be different from s). It is then passed as a reference image (of size w x h x d x N) for the given expression.
Function resize(A,wA,hA,dA,sA,nwA,_nhA,_ndA,_nsA,_interpolation,_boundary_conditions,_ax,_ay,_az,_ac) is an extended version of the resize() function. It lets you resize the vector A, treated as an image of size (ow,oh,od,os) as a new image of size (nw,nh,nd,ns), with specified resizing options.
Function warp(A,wA,hA,dA,sA,B,wB,hB,dB,sB,_mode,_interpolation,_boundary_conditions) returns the warped version of the image A (of size (wA,hA,dA,sA), treated as a vector of size (wA*hA*dA*sA) by the warping field B (of size (wB,hB,dB,sB)). The resulting image has size (wB,hB,dB,sA). This is the math evaluator equivalent of command warp.
Function index(A,P,nb_channelsP,_dithering,_map_colors) returns the indexed version of the image A by the colormap P. This is the math evaluator equivalent of command index.
Function permute(A,wA,hA,dA,sA,permutation) returns a permuted version of the image A (of size (wA,hA,dA,sA), treated as a vector of size wA*hA*dA*sA). This is the math evaluator equivalent of command permute.
Function mirror(A,wA,hA,dA,sA,axes_string) returns a mirrored version of the image A (of size (wA,hA,dA,sA), treated as a vector of size wA*hA*dA*sA). This is the math evaluator equivalent of command mirror.
Function cumulate(A,wA,hA,dA,sA,_axes_string) returns a cumulated version of the image A (of size (wA,hA,dA,sA), treated as a vector of size wA*hA*dA*sA). This is the math evaluator equivalent of command cumulate.
Function histogram(A,nb_levels,_min_value,_max_value) returns the histogram of the vector A. This is the math evaluator equivalent of command histogram.
Function equalize(A,nb_levels,_min_value,_max_value) returns the equalized version of the vector A. This is the math evaluator equivalent of command equalize.
Function normalize(A,_min_value,_max_value) returns the normalized version of the vector A. This is the math evaluator equivalent of command normalize.
Function mproj(S,nb_colsS,D,nb_colsD,method,max_iter,max_residual) projects a matrix S onto a dictionary (matrix) D. This is the math evaluator equivalent of command mproj.
Functions fft(R,I,w,h,d,s,_'axis)' computes the Fast Fourier Transform of the complex pair [R,I], treated as images of size (w,h,d,s). Inverse fft is computed with similar function ifft(). These functions replace the content of R and I in-place.
This is the math evaluator equivalent of commands fft and ifft.Function shift(A,wA,hA,dA,sA,_dx,_dy,_dz,_dc,_boundary_conditions) returns a shifted version of the vector A, treated as an image of size (wA,hA,dA,sA). This is the math evaluator equivalent of command shift.
Function noise(A,amplitude,_noise_type) returns the noisy version of the vector A. This is the math evaluator equivalent of command noise.
Function rand(#size,_min_value,_max_value,_pdf,_precision) returns a vector of size random values. This is the math evaluator equivalent of command rand.
String manipulation:
Character strings are defined as vector objects and can then be managed as such. Dedicated functions and initializers to manage strings exist:['string'] and 'string' define a vector whose values are the character codes of the given character string (e.g. 'foo' is equal to [ 102,111,111 ]).
_'character' returns the ASCII code of the given character (e.g. _'A' is equal to 65).
A special case happens for empty strings: Values of both expressions [''] and '' are 0.
Functions lowercase() and uppercase() return string with all string characters lowercased or uppercased.
Function s2v(str,_starting_index,_is_strict) parses string str and returns the value contained in it.
Function v2s(expr,_nb_digits,_siz) returns a vector of size siz which contains the character representation of values described by expression expr. nb_digits can be { <-1:0-Padding of integers | -1:Auto-reduced | 0:All | >0:Max number of digits }.
Function echo(str1,str2,...,strN) prints the concatenation of given string arguments on the console.
Function string(_#siz,str1,str2,...,strN) generates a vector corresponding to the concatenation of given string/number arguments.
Dynamic arrays:
A dynamic array is defined as a one-column (or empty) image [ind] in the image list. It allows elements to be added or removed, each element having the same dimension (which is actually the number of channels of image [ind]). Dynamic arrays adapt their size to the number of elements they contain.A dynamic array can be manipulated in a math expression, with the following functions:
da_size(_#ind): Returns the number of elements in dynamic array [ind].
da_back(_#ind): Returns the last element of the dynamic array [ind].
da_insert(_#ind,pos,elt_1,_elt_2,...,_elt_N): Insert N new elements elt_k starting from index pos in dynamic array [ind].
da_push(_#ind,elt1,_elt2,...,_eltN): Insert N new elements elt_k at the end of dynamic array [ind].
da_pop(_#ind): Same as da_back() but also remove last element from the dynamic array [ind].
da_push_heap(_#ind,elt1,_elt2,...,_eltN) and da_pop_heap(_#ind) do the same but for a dynamic array seen as a min-heap structure.
da_insert_n(_#ind,n,pos,elt_1,_elt_2,...,_elt_N), da_push_n(_#ind,n,elt1,_elt2,...,_eltN) and da_push_heap_n(_#ind,n,elt1,_elt2,...,_eltN) are variants that insert the given elements consecutively, n times. If no elements are given, they insert n empty elements.
da_remove(_#ind,_start,_end): Remove elements located between indices start and end (included) in dynamic array [ind].
da_freeze(_#ind): Convert a dynamic array into a 1-column image with height da_size(#ind).
The value of the k-th element of dynamic array [ind] is retrieved with i[_#ind,k] (if the element is a scalar value), or I[_#ind,k] (if the element is a vector).
In the functions above, argument #ind may be omitted in which case it is assumed to be #-1.
Special operators:
;: expression separator. The returned value is always the last encountered expression. For instance expression 1;2;pi is evaluated as pi.
=: variable assignment. Variables in mathematical parser can only refer to numerical values (vectors or scalars). Variable names are case-sensitive. Use this operator in conjunction with ; to define more complex evaluable expressions, such as
t = cos(x); 3*t^2 + 2*t + 1
These variables remain local to the mathematical parser and cannot be accessed outside the evaluated expression.Variables defined in math parser may have a constant property, by specifying keyword const before the variable name (e.g. 'const foo = pi/4;'). The value assigned to such a variable must be a constant scalar. Constant variables allow certain types of optimizations in the math JIT compiler.
Specific functions:
addr(expr): returns the pointer address to the given expression expr.
o2c(_#ind,offset,_boundary_conditions) and c2o(_#ind,x,_y,_z,_c,_boundary_conditions): Convert image offset to image coordinates and vice-versa. Argument boundary_conditions can be { 0:None | 1:Return -1 if out-of-range }.
fill(target,expr) or fill(target,index_name,expr) fills the vector variable target, using the given expression, e.g. V = vector16(); fill(V,k,k^2 + k + 1);. This is basically equivalent to: for (index_name = 0, index_name<size(target), ++index_name, target[index_name] = expr);.
fill(target,w,h,d,s,'expr)' fills the vector variable target, treated as an image of size (w,h,d,s), using the given expression.
u(max) or u(min,max,_include_min,_include_max): returns a random value in range 0...max or min...max, following a uniform distribution. Each range extremum can be included (default) in the distribution or not.
v(max) or v(min,max,_include_min,_include_max) do the same but returns an integer in specified range.
f2ui(value) and ui2f(value): Convert a large unsigned integer as a negative floating-point value (and vice-versa), so that 32-bit floats can be used to store large integers while keeping a unitary precision.
i(_a,_b,_c,_d,_interpolation_type,_boundary_conditions): returns the value of the pixel located at position (a,b,c,d) in the current image, if any (0 otherwise). interpolation_type can be { 0:Nearest neighbor | 1:Linear | 2:Cubic }. boundary_conditions can be { 0:Dirichlet | 1:Neumann | 2:Periodic | 3:Mirror }. Omitted coordinates are replaced by their default values which are respectively x, y, z, c, interpolation and boundary. For instance command
fill 0.5*(i(x+1)-i(x-1))
will estimate the X-derivative of an image with a classical finite difference scheme.j(_dx,_dy,_dz,_dc,_interpolation_type,_boundary_conditions) does the same for the pixel located at position (x+dx,y+dy,z+dz,c+dc) (pixel access relative to the current coordinates).
i[offset,_boundary_conditions] returns the value of the pixel located at offset in the associated image buffer (or 0 if offset is out-of-bounds).
j[offset,_boundary_conditions] does the same for an offset relative to the current pixel coordinates (x,y,z,c).
i(#ind,_x,_y,_z,_c,_interpolation,_boundary_conditions), j(#ind,_dx,_dy,_dz,_dc,_interpolation,_boundary_conditions), i[#ind,offset,_boundary_conditions] and i[offset,_boundary_conditions] are similar expressions used to access pixel values for any numbered image [ind] in the list.
I/J[_#ind,offset,_boundary_conditions] and I/J(_#ind,_x,_y,_z,_interpolation,_boundary_conditions) do the same as i/j[_#ind,offset,_boundary_conditions] and i/j(_#ind,_x,_y,_z,_c,_interpolation,_boundary_conditions) but return a vector instead of a scalar (e.g. a vector [ R,G,B ] for a pixel at (a,b,c) in a color image).
crop(_#ind,_x,_y,_z,_c,_dx,_dy,_dz,_dc,_boundary_conditions) returns a vector whose values come from the cropped region of image [ind] (or from default image selected if ind is not specified). Cropped region starts from point (x,y,z,c) and has a size of (dx,dy,dz,dc). Arguments for coordinates and sizes can be omitted if they are not ambiguous (e.g. crop(#ind,x,y,dx,dy) is a valid invocation of this function).
* crop(S,w,h,d,s,_x,_y,_z,_c,_dx,_dy,_dz,_dc,_boundary_conditions) does the same but extracts the cropped data from a vector S, treated as an image of size (w,h,d,s).draw(_#ind,S,_x,_y,_z,_c,_dx,_dy,_dz,_dc,_opacity,_opacity_mask,_max_opacity_mask) draws a sprite S in image [ind] (or in default image selected if ind is not specified) at coordinates (x,y,z,c).
draw(D,w,h,s,d,S,_x,_y,_z,_c,_dx,_dy,_dz,_dc,_opacity,_M,_max_M) does the same but draw the sprite S in the vector D, treated as an image of size (w,h,d,s).
polygon(_#ind,nb_vertices,coords,_opacity,_color) draws a filled polygon in image [ind] (or in default image selected if ind is not specified) at given coordinates. It draws a single line if nb_vertices is set to 2.
polygon(_#ind,-nb_vertices,coords,_opacity,_pattern,_color) draws an outlined polygon in image [ind] (or in default image selected if ind is not specified) at given coordinates and with line pattern. It draws a single line if nb_vertices is set to 2.
ellipse(_#ind,xc,yc,radius1,_radius2,_angle,_opacity,_color) draws a filled ellipse in image [ind] (or in default image selected if ind is not specified) with given coordinates.
ellipse(_#ind,xc,yc,-radius1,-_radius2,_angle,_opacity,_pattern,_color) draws an outlined ellipse in image [ind] (or in default image selected if ind is not specified).
flood(_#ind,_x,_y,_z,_tolerance,_is_high_connectivity,_opacity,_color) performs a flood fill in image [ind] (or in default image selected if ind is not specified) with given coordinates. This is the math evaluator equivalent of command flood.
resize(#ind,w,_h,_d,_s,_interp,_boundary_conditions,_cx,_cy,_cz,_cc) resizes an image of the associated list with given dimension and interpolation method. When using this function, you should consider retrieving the (non-constant) image dimensions using the dynamic functions w(_#ind), h(_#ind), d(_#ind), s(_#ind), wh(_#ind), whd(_#ind) and whds(_#ind) instead of the corresponding constant variables.
if(condition,expr_then,_expr_else): returns value of expr_then or expr_else, depending on the value of condition { 0:False | other:True }. expr_else can be omitted in which case 0 is returned if the condition does not hold. Using the ternary operator condition?expr_then[:expr_else] gives an equivalent expression. For instance, G'MIC commands
fill if(!(x%10),255,i)
and fill x%10?i:255
both draw blank vertical lines on every 10th column of an image.do(expression,_condition) repeats the evaluation of expression until condition vanishes (or until a break() instruction is encountered if no condition is specified). For instance, the expression:
if(N<2,N,n=N-1;F0=0;F1=1;do(F2=F0+F1;F0=F1;F1=F2,n=n-1))
returns the N-th value of the Fibonacci sequence, for N>=0 (e.g., 46368 for N=24). do(expression,condition) always evaluates the expression at least once, then checks for the loop condition. When done, it returns the last value of expression.for(init,condition,_procedure,body) first evaluates the expression init, then iteratively evaluates body (followed by procedure if specified) while condition holds (i.e. not zero). It may happen that no iterations are done, in which case the function returns nan. Otherwise, it returns the last value of body. For instance, the expression:
if(N<2,N,for(n=N;F0=0;F1=1,n=n-1,F2=F0+F1;F0=F1;F1=F2))
returns the N-th value of the Fibonacci sequence, for N>=0 (e.g., 46368 for N=24).while(condition,expression) is exactly the same as for(init,condition,expression) without the specification of an initializing expression.
repeat(nb_iters,expr) or fill(nb_iters,iter_name,expr) run nb_iters iterations of the given expression expr, e.g. V = vector16(); repeat(16,k,V[k] = k^2 + k + 1);. It is basically equivalent to: for (iter_name = 0, iter_name<nb_iters, ++iter_name, expr);.
break() and continue() respectively terminate or continue execution of the current loop or block.
fsize('filename)' returns the size of the given filename (or -1 if file does not exist).
date(attr,'path)' returns the date attribute for the given path (file or directory), with attr being { 0:Year | 1:Month | 2:Day | 3:Day of week | 4:Hour | 5:Minute | 6:Second }, or a vector of those values.
date(_attr) returns the given attribute for the current (locale) date (attributes being { 0...6:Same meaning as above | 7:Milliseconds }).
epoch(_year,_month,_day,_hour,_minute,_second) converts a date into Epoch. If no arguments are specified, current Epoch is returned.
print(expr1,expr2,...) or print(#ind) prints the value of the given expressions (or image information) on the console, and returns the value of the last expression (or nan in case of an image). Function prints(expr) also prints the string composed of the character codes defined by the vector-valued expression (e.g. prints('Hello)').
debug(expression) prints detailed debug info about the sequence of operations done by the math parser to evaluate the expression (and returns its value).
display(_X,_w,_h,_d,_s) or display(#ind) displays the contents of the vector X (or given image) and wait for user events. If no arguments are given, a memory snapshot of the math parser environment is displayed instead.
begin(expression) and end(expression) evaluate the given expressions only once, respectively at the beginning and end of the evaluation procedure, and this, even when multiple evaluations are required (e.g. in 'fill ">begin(foo = 0); ++foo"').
copy(dest,src,_nb_elts,_inc_d,_inc_s,_opacity) copies an entire memory block of nb_elts elements starting from a source value src to a specified destination dest, with increments defined by inc_d and inc_s respectively for the destination and source pointers.
stats(_#ind) returns the statistics vector of the running image [ind], i.e the vector [ im,iM,ia,iv,xm,ym,zm,cm,xM,yM,zM,cM,is,ip,in ] (15 values).
stats(X,w,h,d,s) returns the statistics vector of the vector X, treated as an image of size (w,h,d,s).
ref(expr,a) references given expression expr as variable name a.
unref(a,b,...) destroys references to the named variable given as arguments.
breakpoint() inserts a possible computation breakpoint (useless with the cli interface).
_(comment) expr just returns expression expr (useful for inserting inline comments in math expressions).
run('pipeline)' executes the G'MIC pipeline as if it was called outside the currently evaluated expression.
set('variable_name',A) sets the G'MIC variable $variable_name with the value of expression A. If A is a vector variable, it is assumed to encode a string.
store('variable_name',A,_w,_h,_d,_s,_is_compressed) transfers the data of vector A as a (w,h,d,s) image to the G'MIC variable $variable_name. Thus, the data becomes available outside the math expression (that is equivalent to using the regular command store, but directly in the math expression).
get('variable_name',_size,_return_as_string) returns the value of the variable, as a vector of size values, or as a scalar (if size is zero or not specified).
name(_#ind,size) returns a vector of size size, whose values are the characters codes of the name of image [ind] (or default image selected if ind is not specified).
correlate(I,wI,hI,dI,sI,K,wK,hK,dK,sK,_boundary_conditions,_is_normalized,_channel_mode,_xcenter,_ycenter,_zcenter,_xstride,_ystride,_zstride,_xdilation,_ydilation,_zdilation,_xoffset,_yoffset,_zoffset,_xsize,_ysize,_zsize) returns the correlation, unrolled as a vector, of the (wI,hI,dI,sI)-sized image I with the (wK,hK,dK,sK)-sized kernel K (the meaning of the other arguments are the same as in command correlate). Similar function convolve(...) is also defined for computing the convolution between I and K.
User-defined macros:
Custom macro functions can be defined in a math expression, using the assignment operator =, e.g.
foo(x,y) = cos(x + y); result = foo(1,2) + foo(2,3)
Trying to override a built-in function (e.g. abs()) has no effect.
Overloading macros with different number of arguments is possible. Re-defining a previously defined macro with the same number of arguments discards its previous definition.
Macro functions are processed as macros by the mathematical evaluator. You should avoid invoking them with arguments that are themselves results of assignments or self-operations. For instance,
foo(x) = x + x; z = 0; foo(++z)
returns 4 rather than expected value 2.When substituted, macro arguments are placed inside parentheses, except if a number sign # is located just before or after the argument name. For instance, expression
foo(x,y) = x*y; foo(1+2,3)
returns 9 (being substituted as (1+2)*(3)), while expression foo(x,y) = x#*y#; foo(1+2,3)
returns 7 (being substituted as 1+2*3).Number signs # appearing between macro arguments actually act as empty separators. They may be used to force the substitution of macro arguments in unusual places, e.g. as in
str(N) = ['I like N#'];
Macros with variadic arguments can be defined, by specifying a single argument name followed by .... For instance,
foo(args...) = sum([ args ]^2);
defines a macro that returns the sum of its squared arguments, so foo(1,2,3) returns 14 and foo(4,5) returns 41.Multi-threaded and in-place evaluation:
If your images are large enough and you have several CPU cores available, it is possible that the math expression passed to a fill, eval or input commands can be evaluated in parallel, using multiple computation threads.
G'MIC tries to auto-detect if an expression can be parallelized, and if it can be evaluated in-place (otherwise, a temporary copy of the image is allocated). However, this auto-detection can be overridden, by starting the mathematical expression for the fill or eval commands, with a single character, that can be:
*: Evaluate expression in parallel, possibly using a temporary image copy.
:: Evaluate expression in parallel, but in-place.
+: Evaluate expression in a single thread, possibly using a temporary image copy (in scanline order).
>: Evaluate expression in a single thread, but in-place (in scanline order).
<: Evaluate expression in a single thread, but in-place (in reverse scanline order).
Beware, depending on the amount of data to process, parallel evaluations may be slower than using single-thread evaluations (e.g. for small images).
For parallel evaluations, function critical(expr) serializes execution of the given sub-expression expr in a single thread at a time.
begin_t(expr) and end_t(expr) evaluate the given expression once for each running thread (so possibly several times) at the beginning and the end of the evaluation procedure.
merge(variable,operator) specifies that the local thread values requests merging, with the given operator, when all threads have finished computing.
Expressions i(_#ind,x,_y,_z,_c)=value, j(_#ind,x,_y,_z,_c)=value, i[_#ind,offset]=value and j[_#ind,offset]=value set a pixel value at a different location than the running one in the image [ind] (or in the current image if argument #ind is omitted), either with global coordinates/offsets (with i(...) and i[...]), or relatively to the current position (x,y,z,c) (with j(...) and j[...]). These expressions always return value.


Home
Download
News
Mastodon
Bluesky
X
Summary - 17 Years
Summary - 16 Years
Summary - 15 Years
Summary - 13 Years
Summary - 11 Years
Summary - 10 Years
Resources
Technical Reference
Scripting Tutorial
Video Tutorials
Wiki Pages
Image Gallery
Color Presets
Using libgmic
G'MIC Online
Community
Discussion Forum (Pixls.us)
GimpChat
IRC
Report Issue