API Reference

G’MIC image processing library Python binary module.

Use gmic.run or gmic.Gmic to run G’MIC commands inside the G’MIC C++ interpreter, manipulate gmic.GmicImage which has numpy/PIL input/output support, assemble lists of gmic.GmicImage items inside read-writeable pure-Python list objects.

class gmic.Gmic

Bases: object

run(command, images=None, image_names=None)

Run G’MIC interpreter following a G’MIC language command(s) string, on 0 or more namable GmicImage items.

Note (single-image short-hand calling): if images is a GmicImage, then image_names must be either a str or be omitted.

Example

Here is a long example describing several use cases:

import gmic
import struct
import random
instance1 = gmic.Gmic('echo_stdout \'instantiation and run all in one\')
instance2 = gmic.Gmic()
instance2.run('echo_stdout \'hello world\'') # G'MIC command without images parameter
a = gmic.GmicImage(struct.pack(*('256f',) + tuple([random.random() for a in range(256)])), 16, 16) # Build 16x16 greyscale image
instance2.run('blur 12,0,1 resize 50%,50%', a) # Blur then resize the image
a._width == a._height == 8 # The image is half smaller
instance2.run('display', a) # If you have X11 enabled (linux only), show the image in a window
image_names = ['img_' + str(i) for i in range(10)] # You can also name your images if you have several (optional)
images = [gmic.GmicImage(struct.pack(*((str(w*h)+'f',) + (i*2.0,)*w*h)), w, h) for i in range(10)] # Prepare a list of image
instance1.run('add 1 print', images, image_names) # And pipe those into the interpreter
instance1.run('blur 10,0,1 print', images[0], 'my_pic_name') # Short-hand 1-image calling style
Parameters
  • command (str) – An image-processing command in the G’MIC language

  • images (Optional[Union[List[gmic.GmicImage], gmic.GmicImage]]) – A list of GmicImage items that G’MIC will edit in place, or a single gmic.GmicImage which will used for input only. Defaults to None. Put a list variable here, not a plain []. If you pass a list, it can be empty if you intend to fill or complement it using your G’MIC command.

  • image_names (Optional[List<str>]) – A list of names for the images, defaults to None. In-place editing by G’MIC can happen, you might want to pass your list as a variable instead.

Returns

Returns None or raises a GmicException.

Return type

None

Raises

GmicException – This translates’ G’MIC C++ same-named exception. Look at the exception message for details.

exception gmic.GmicException

Bases: Exception

Only exception class of the Gmic module.

This wraps G’MIC’s C++ gmic_exception. Refer to the exception message itself.

class gmic.GmicImage(data=None, width=1, height=1, depth=1, spectrum=1, shared=False)

Bases: object

Simplified mapping of the C++ gmic_image type. Stores a binary buffer of data, a height, width, depth, spectrum.

Example

Several ways to use a GmicImage simply:

import gmic
empty_1x1x1_black_image = gmic.GmicImage() # or gmic.GmicImage(None,1,1,1,1) for example
import struct
i = gmic.GmicImage(struct.pack('2f', 0.0, 1.5), 1, 1) # 2D 1x1 image
gmic.run('add 1', i) # GmicImage injection into G'MIC's interpreter
i # Using GmicImage's repr() string representation
# Output: <gmic.GmicImage object at 0x7f09bfb504f8 with _data address at 0x22dd5b0, w=1 h=1 d=1 s=1 shared=0>
i(0,0) == 1.0 # Using GmicImage(x,y,z) pixel reading operator after initialization
gmic.run('resize 200%,200%', i) # Some G'MIC operations may reallocate the image buffer in place without risk
i._width == i._height == 2 # Use the _width, _height, _depth, _spectrum, _data, _data_str, _is_shared read-only attributes
Parameters
  • data (Optional[bytes]) – Raw data for the image (must be a sequence of 4-bytes floats blocks, with as many blocks as all the dimensions multiplied together).

  • width (Optional[int]) – Image width in pixels. Defaults to 1.

  • height (Optional[int]) – Image height in pixels. Defaults to 1.

  • depth (Optional[int]) – Image height in pixels. Defaults to 1.

  • spectrum (Optional[int]) – Number of channels per pixel. Defaults to 1.

  • shared (Optional[bool]) – C++ option: whether the buffer should be shareable between several GmicImages and operations. Defaults to False.

Note

GmicImage(x=0, y=0, z=0, s=0)

This instance method allows you to read pixels in a GmicImage for given coordinates.

You can read, but cannot write pixel values by passing some or all coordinates the following way:

import gmic
images = []
gmic.run("sp apples", images)
image = images[0]
print(image(0,2,0,2)) # or image(y=2,z=2)
print(image(0,0,0,0)) # or image()
for x in range(image._width):
    for y in range(image._height):
        for z in range(image._depth):
            for c in range(image._spectrum):
                print(image(x,y,z,c))
__copy__()

Copy method for copy.copy() support. Deepcopying and pickle-ing are not supported.

from_PIL(pil_image)

Make a GmicImage from a 2D PIL.Image.Image object. Equates to gmic.GmicImage.from_numpy_helper(numpy.array(pil_image), deinterleave=True). Will import PIL.Image and numpy for conversion.

Parameters

pil_image (PIL.Image.Image) – An image to convert into GmicImage.

Returns

A new gmic.GmicImage based on the input PIL.Image.Image data.

Return type

gmic.GmicImage

from_numpy(numpy_array)

Make a GmicImage from a 1-4 dimensions numpy.ndarray. Simplified version of GmicImage.from_numpy_helper with deinterleave=True.

Parameters

numpy_array (numpy.ndarray) – A non-empty 1D-4D Numpy array.

Returns

A new GmicImage based the input numpy.ndarray data.

Return type

GmicImage

Raises

GmicException, TypeError – Look at the exception message for details. Matrices with dimensions <1D or >4D will be rejected.

from_numpy_helper(numpy_array, deinterleave=False, permute='')

Make a GmicImage from a 1-4 dimensions numpy.ndarray.

G’MIC works with (width, height, depth, spectrum/channels) matrix layout, with 32bit-float pixel values deinterleaved (ie. RRR,GGG,BBB). If your matrix is less than 4D, G’MIC will tentatively add append void dimensions to it (eg. for a shape of (3,1) -> (3,1,1,1)). You can avoid this by using numpy.expand_dims or numpy.atleast_*d functions yourself first. If your pixel values (ie. numpy.ndarray.dtype) are not in a float32 format, G’MIC will tentatively call numpy.astype(numpy_array, numpy.float32) to cast its contents first.

Example

Several ways to use a GmicImage simply:

import gmic
empty_1x1x1_black_image = gmic.GmicImage() # or gmic.GmicImage(None,1,1,1,1) for example
import struct
i = gmic.GmicImage(struct.pack('2f', 0.0, 1.5), 1, 1) # 2D 1x1 image
gmic.run('add 1', i) # GmicImage injection into G'MIC's interpreter
i # Using GmicImage's repr() string representation
# Output: <gmic.GmicImage object at 0x7f09bfb504f8 with _data address at 0x22dd5b0, w=1 h=1 d=1 s=1 shared=0>
i(0,0) == 1.0 # Using GmicImage(x,y,z) pixel reading operator after initialization
gmic.run('resize 200%,200%', i) # Some G'MIC operations may reallocate the image buffer in place without risk
i._width == i._height == 2 # Use the _width, _height, _depth, _spectrum, _data, _data_str, _is_shared read-only attributes
Parameters
  • numpy_array (numpy.ndarray) – A non-empty 1D-4D Numpy array.

  • deinterleave (Optional[bool]) – If True, pixel channel values will be deinterleaved inside the GmicImage data. If False, pixel channels vector values will be untouched. Defaults to False.

  • permute (Optional[str]) – If non-empty, a G’MIC permute operation will be run with this parameter (eg. yxzc) on the input matrix before saving into the GmicImage. See https://gmic.eu/reference.shtml#permute Defaults to “” (no permutation).

Returns

A new GmicImage based the input numpy.ndarray data.

Return type

GmicImage

Raises

GmicException, TypeError – Look at the exception message for details. Matrices with dimensions <1D or >4D will be rejected.

from_skimage()

GmicImage.from_numpy_helper(numpy_array, deinterleave=False, permute=’’)

Make a GmicImage from a 1-4 dimensions numpy.ndarray.

G’MIC works with (width, height, depth, spectrum/channels) matrix layout, with 32bit-float pixel values deinterleaved (ie. RRR,GGG,BBB). If your matrix is less than 4D, G’MIC will tentatively add append void dimensions to it (eg. for a shape of (3,1) -> (3,1,1,1)). You can avoid this by using numpy.expand_dims or numpy.atleast_*d functions yourself first. If your pixel values (ie. numpy.ndarray.dtype) are not in a float32 format, G’MIC will tentatively call numpy.astype(numpy_array, numpy.float32) to cast its contents first.

Example

Several ways to use a GmicImage simply:

import gmic
empty_1x1x1_black_image = gmic.GmicImage() # or gmic.GmicImage(None,1,1,1,1) for example
import struct
i = gmic.GmicImage(struct.pack('2f', 0.0, 1.5), 1, 1) # 2D 1x1 image
gmic.run('add 1', i) # GmicImage injection into G'MIC's interpreter
i # Using GmicImage's repr() string representation
# Output: <gmic.GmicImage object at 0x7f09bfb504f8 with _data address at 0x22dd5b0, w=1 h=1 d=1 s=1 shared=0>
i(0,0) == 1.0 # Using GmicImage(x,y,z) pixel reading operator after initialization
gmic.run('resize 200%,200%', i) # Some G'MIC operations may reallocate the image buffer in place without risk
i._width == i._height == 2 # Use the _width, _height, _depth, _spectrum, _data, _data_str, _is_shared read-only attributes
Parameters
  • numpy_array (numpy.ndarray) – A non-empty 1D-4D Numpy array.

  • deinterleave (Optional[bool]) – If True, pixel channel values will be deinterleaved inside the GmicImage data. If False, pixel channels vector values will be untouched. Defaults to False.

  • permute (Optional[str]) – If non-empty, a G’MIC permute operation will be run with this parameter (eg. yxzc) on the input matrix before saving into the GmicImage. See https://gmic.eu/reference.shtml#permute Defaults to “” (no permutation).

Returns

A new GmicImage based the input numpy.ndarray data.

Return type

GmicImage

Raises

GmicException, TypeError – Look at the exception message for details. Matrices with dimensions <1D or >4D will be rejected.

to_PIL(astype=numpy.uint8, squeeze_shape=True, mode='RGB')

Make a 2D 8-bit per pixel RGB PIL.Image from any GmicImage. Equates to PIL.Image.fromarray(self.to_numpy_helper(astype=astype, squeeze_shape=squeeze_shape, interleave=True, permute='zyxc'), mode). Will import PIL.Image and numpy.

This method uses numpy for conversion. Thus astype is used in a numpy.ndarray.astype()` conversion pass and samewise for ``squeeze_shape. :param astype: Will be used for casting your image’s pixel. :type astype: type :param squeeze_shape: if True, your image shape has ‘1’ components removed, is usually necessary to convert from G’MIC 3D to PIL.Image 2D only. :type squeeze_shape: bool :param mode: the PIL Image mode to use. see https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes :type mode: str

Returns

A new PIL.Image based on the instance GmicImage data from which you call this method.

Return type

PIL.Image

to_numpy()

Make a numpy.ndarray from a GmicImage. Simplified version of GmicImage.to_numpy_helper with interleave=True.

Returns

A new numpy.ndarray based the input GmicImage data.

Return type

numpy.ndarray

to_numpy_helper(astype=numpy.float32, interleave=False, permute='', squeeze_shape=False)

Make a numpy.ndarray from a GmicImage. G’MIC does not squeeze dimensions internally, so unless you use the squeeze_shape flag calling numpy.squeeze for you, the output matrix will be 4D.

Parameters
  • astype (numpy.dtype) – The type to which G’MIC’s float32 pixel values will cast to for the output matrix.

  • interleave (Optional[bool]) – If True, pixel channel values will be interleaved (ie. RGB, RGB, RGB) within the numpy array. If False, pixel channels vector values will be untouched/deinterleaved (ie. RRR,GGG,BBB). Defaults to False.

  • permute (Optional[str]) – If non-empty, a G’MIC permute operation will be run with this parameter (eg. yxzc) on the output matrix before saving into the GmicImage. See https://gmic.eu/reference.shtml#permute Defaults to “” (ie. no permutation).

Returns

A new numpy.ndarray based the input GmicImage data.

Return type

numpy.ndarray

to_skimage()

GmicImage.to_numpy_helper(astype=numpy.float32, interleave=False, permute=’’, squeeze_shape=False)

Make a numpy.ndarray from a GmicImage. G’MIC does not squeeze dimensions internally, so unless you use the squeeze_shape flag calling numpy.squeeze for you, the output matrix will be 4D.

Parameters
  • astype (numpy.dtype) – The type to which G’MIC’s float32 pixel values will cast to for the output matrix.

  • interleave (Optional[bool]) – If True, pixel channel values will be interleaved (ie. RGB, RGB, RGB) within the numpy array. If False, pixel channels vector values will be untouched/deinterleaved (ie. RRR,GGG,BBB). Defaults to False.

  • permute (Optional[str]) – If non-empty, a G’MIC permute operation will be run with this parameter (eg. yxzc) on the output matrix before saving into the GmicImage. See https://gmic.eu/reference.shtml#permute Defaults to “” (ie. no permutation).

Returns

A new numpy.ndarray based the input GmicImage data.

Return type

numpy.ndarray

gmic.run(command, images=None, image_names=None)

Run the G’MIC interpreter with a G’MIC language command(s) string, on 0 or more nameable GmicImage(s). This is a short-hand for calling gmic.Gmic().run with the exact same parameters signature.

Note (single-image short-hand calling): if images is a GmicImage, then image_names must be either a str or be omitted.

Note (interpreter warm-up): calling gmic.run multiple times is inefficient as it spawns then drops a new G’MIC interpreter instance for every call. For better performance, you can tie a gmic.Gmic G’MIC interpreter instance to a variable instead and call its run method multiple times. Look at gmic.Gmic.run for more information.

Example

Several ways to use the module-level gmic.run() function:

import gmic
import struct
import random
gmic.run('echo_stdout \'hello world\'') # G'MIC command without images parameter
a = gmic.GmicImage(struct.pack(*('256f',) + tuple([random.random() for a in range(256)])), 16, 16) # Build 16x16 greyscale image
gmic.run('blur 12,0,1 resize 50%,50%', a) # Blur then resize the image
a._width == a._height == 8 # The image is half smaller
gmic.run('display', a) # If you have X11 enabled (linux only), show the image in a window
image_names = ['img_' + str(i) for i in range(10)] # You can also name your images if you have several (optional)
images = [gmic.GmicImage(struct.pack(*((str(w*h)+'f',) + (i*2.0,)*w*h)), w, h) for i in range(10)] # Prepare a list of image
gmic.run('add 1 print', images, image_names) # And pipe those into the interpreter
gmic.run('blur 10,0,1 print', images[0], 'my_pic_name') # Short-hand 1-image calling style
Parameters
  • command (str) – An image-processing command in the G’MIC language

  • images (Optional[Union[List[gmic.GmicImage], gmic.GmicImage]]) – A list of GmicImage items that G’MIC will edit in place, or a single gmic.GmicImage which will used for input only. Defaults to None. Put a list variable here, not a plain []. If you pass a list, it can be empty if you intend to fill or complement it using your G’MIC command.

  • image_names (Optional[List<str>]) – A list of names for the images, defaults to None. In-place editing by G’MIC can happen, you might want to pass your list as a variable instead.

Returns

Returns None or raises a GmicException.

Return type

None

Raises

GmicException – This translates’ G’MIC C++ same-named exception. Look at the exception message for details.