mt.opencv.image

An self-contained image.

Functions

  • immload_asyn(): An asyn function that loads an image with metadata.

  • immload(): Loads an image with metadata.

  • immload_header_asyn(): An asyn function that loads the header of an image with metadata.

  • immload_header(): Loads the header of an image with metadata.

  • immsave_asyn(): An asyn function that saves an image with metadata to file.

  • immsave(): Saves an image with metadata to file.

  • imload(): An asyn function wrapping on cv.imread().

  • imsave(): An asyn function wrapping on cv.imwrite().

  • im_float2ubyte(): Converts an image with a float dtype into an image with an ubyte dtype.

  • im_ubyte2float(): Converts an image with an ubyte dtype into an image with a float32 dtype.

async mt.opencv.image.immload_asyn(fp, context_vars: dict = {})

An asyn function that loads an image with metadata.

Parameters:
  • fp (object) – string representing a local filepath or an open readable file-like object

  • context_vars (dict) – a dictionary of context variables within which the function runs. It must include context_vars[‘async’] to tell whether to invoke the function asynchronously or not.

Returns:

the loaded image with metadata

Return type:

Image

Raises:

OSError – if an error occured while loading

Notes

As of 2022/06/18, the file can be in HDF5 format or JSON format.

mt.opencv.image.immload(fp)

Loads an image with metadata.

Parameters:

fp (object) – string representing a local filepath or an open readable file handle

Returns:

the loaded image with metadata

Return type:

Image

Raises:

OSError – if an error occured while loading

async mt.opencv.image.immload_header_asyn(fp, context_vars: dict = {})

An asyn function that loads the header of an image with metadata.

Parameters:
  • fp (object) – string representing a local filepath or an open readable file-like object

  • context_vars (dict) – a dictionary of context variables within which the function runs. It must include context_vars[‘async’] to tell whether to invoke the function asynchronously or not.

Returns:

a dictionary containing keys [‘pixel_format’, ‘width’, ‘height’, meta’]

Return type:

dict

Raises:

OSError – if an error occured while loading

Notes

As of 2022/06/18, the file can be in HDF5 format or JSON format.

mt.opencv.image.immload_header(fp)

Loads the header of an image with metadata.

Parameters:
  • fp (object) – string representing a local filepath or an open readable file-like object

  • context_vars (dict) – a dictionary of context variables within which the function runs. It must include context_vars[‘async’] to tell whether to invoke the function asynchronously or not.

Returns:

a dictionary containing keys [‘pixel_format’, ‘width’, ‘height’, meta’]

Return type:

dict

Raises:

OSError – if an error occured while loading

Notes

As of 2022/06/18, the file can be in HDF5 format or JSON format.

async mt.opencv.image.immsave_asyn(image: Image, fp: str, file_mode: int = 436, image_codec: str = 'png', quality: int | None = None, context_vars: dict = {}, file_format: str = 'hdf5', file_write_delayed: bool = False, logger=None)

An asyn function that saves an image with metadata to file.

Parameters:
  • imm (Image) – an image with metadata

  • fp (str) – local filepath to save the content to. If the file format is ‘json’, fp can also be a file-like object.

  • file_mode (int) – file mode to be set to using os.chmod(). If None is given, no setting of file mode will happen.

  • image_codec ({'jpg', 'png'}) – image codec. Currently only ‘jpg’ and ‘png’ are supported.

  • quality (int, optional) – percentage of image quality. For ‘jpg’, it is a value between 0 and 100. For ‘png’, it is a value between 0 and 9. If not provided, the backend default will be used.

  • context_vars (dict) – a dictionary of context variables within which the function runs. It must include context_vars[‘async’] to tell whether to invoke the function asynchronously or not.

  • file_format ({'json', 'hdf5'}) – format to be used for saving the content.

  • file_write_delayed (bool) – Only valid in asynchronous mode and the format is ‘json’. If True, wraps the file write task into a future and returns the future. In all other cases, proceeds as usual.

  • logger (logging.Logger, optional) – logger for debugging purposes

Returns:

In the case of format ‘json’, it is either a future or whatever json.dump() returns, depending on whether the file write task is delayed or not. In the case format ‘hdf5’, it is whatever Image.to_hdf5() returns.

Return type:

asyncio.Future or object

Raises:

OSError – if an error occured while loading

mt.opencv.image.immsave(image, fp, file_mode: int = 436, image_codec: str = 'png', quality: int | None = None, file_format: str = 'hdf5', logger=None)

Saves an image with metadata to file.

Parameters:
  • imm (Image) – an image with metadata

  • fp (object) – string representing a local filepath or an open writable file handle

  • file_mode (int) – file mode to be set to using os.chmod(). Only valid if fp is a string. If None is given, no setting of file mode will happen.

  • image_codec ({'jpg', 'png'}) – image codec. Currently only ‘jpg’ and ‘png’ are supported.

  • quality (int, optional) – percentage of image quality. For ‘jpg’, it is a value between 0 and 100. For ‘png’, it is a value between 0 and 9. If not provided, the backend default will be used.

  • file_format ({'json', 'hdf5'}) – format to be used for saving the content.

  • logger (logging.Logger, optional) – logger for debugging purposes

Raises:

OSError – if an error occured while loading

async mt.opencv.image.imload(filepath: str, flags=6, context_vars: dict = {})

An asyn function wrapping on cv.imread().

Parameters:
  • filepath (str) – Local path to the file to be loaded

  • flags (int) – ‘cv.IMREAD_xxx’ flags, if any. See cv:imread().

  • context_vars (dict) – a dictionary of context variables within which the function runs. It must include context_vars[‘async’] to tell whether to invoke the function asynchronously or not.

Returns:

img – the loaded image

Return type:

numpy.ndarray

See also

cv.imread

wrapped function

async mt.opencv.image.imsave(filepath: str, img: ndarray, params=None, file_mode: int = 436, context_vars: dict = {}, file_write_delayed: bool = False)

An asyn function wrapping on cv.imwrite().

Parameters:
  • filepath (str) – Local path to the file to be saved to

  • img (numpy.ndarray) – the image to be saved

  • params (int) – Format-specific parameters, if any. Like those ‘cv.IMWRITE_xxx’ flags. See cv.imwrite().

  • file_mode (int) – file mode to be set to using os.chmod(). Only valid if fp is a string. If None is given, no setting of file mode will happen.

  • context_vars (dict) – a dictionary of context variables within which the function runs. It must include context_vars[‘async’] to tell whether to invoke the function asynchronously or not.

  • file_write_delayed (bool) – Only valid in asynchronous mode. If True, wraps the file write task into a future and returns the future. In all other cases, proceeds as usual.

Returns:

either a future or the number of bytes written, depending on whether the file write task is delayed or not

Return type:

asyncio.Future or int

Note

Do not use this function to write in PNG format. OpenCV would happily assume the input is BGR or BGRA and then write to PNG under that assumption, which often results in a wrong order.

See also

cv.imwrite

wrapped asynchronous function

mt.opencv.image.im_float2ubyte(img: ndarray, is_float01: bool = True)

Converts an image with a float dtype into an image with an ubyte dtype.

Parameters:
  • img (nd.ndarray) – the image to be converted

  • is_float01 (bool) – whether the pixel values of the float image are in range [0,1] (True) or range [-1,1] (False)

Returns:

the converted image with ubyte dtype

Return type:

nd.ndarray

mt.opencv.image.im_ubyte2float(img: ndarray, is_float01: bool = True, rng: RandomState | bool | None = None)

Converts an image with an ubyte dtype into an image with a float32 dtype.

Parameters:
  • img (nd.ndarray) – the image to be converted

  • is_float01 (bool) – whether the pixel values of the float image are to be in range [0,1] (True) or range [-1,1] (False)

  • rng (numpy.random.RandomState or bool or None) – Whether or not to use an rng to dequantise pixel values from integer to floats. If None or False is provided, we do not add (0,1)-uniform noise to the pixel values. If True is provided, an internal ‘rng’ is created. Otherwise, the provided ‘rng’ is used to generate random numbers.

Returns:

the converted image with float32 dtype

Return type:

nd.ndarray

Classes

  • Image: A self-contained image, where the meta-data associated with the image are kept together with the image itself.

class mt.opencv.image.Image(image, pixel_format='rgb', meta={})

A self-contained image, where the meta-data associated with the image are kept together with the image itself.

Parameters:
  • image (numpy.array) – a 2D image of shape (height, width, nchannels) or (height, width) with dtype uint8

  • pixel_format (str) – one of the keys in the PixelFormat mapping

  • meta (dict) – A JSON-like object. It holds additional keyword parameters associated with the image.

Inheritance

digraph inheritance73c2a03954 { bgcolor=transparent; rankdir=LR; size="8.0, 12.0"; "Image" [URL="#mt.opencv.image.Image",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="A self-contained image, where the meta-data associated with the image are kept together with the image itself."]; }
static from_hdf5(h5_group)

Loads the image from an HDF5 group.

Parameters:

h5_group (h5py.Group) – a h5py.Group object to read from

Returns:

the loaded image with metadata

Return type:

Image

static from_json(json_obj)

Loads the image from a JSON-like object produced by dumps().

Parameters:

json_obj (dict) – the serialised json object

Returns:

the loaded image with metadata

Return type:

Image

to_hdf5(h5_group, image_codec: str = 'jpg', quality: int | None = None)

Dumps the image to a h5py.Group object.

Parameters:
  • h5_group (h5py.Group) – a h5py.Group object to write to

  • image_codec ({'jpg', 'png'}) – image codec. Currently only ‘jpg’ and ‘png’ are supported.

  • quality (int, optional) – percentage of image quality. For ‘jpg’, it is a value between 0 and 100. For ‘png’, it is a value between 0 and 9. If not provided, the backend default will be used.

Raises:
  • ImportError – if h5py is not importable

  • ValueError – if the provided group is not of type h5py.Group

to_json(image_codec: str = 'jpg', quality: int | None = None)

Dumps the image to a JSON-like object.

Parameters:
  • image_codec ({'jpg', 'png'}) – image codec. Currently only ‘jpg’ and ‘png’ are supported.

  • quality (int, optional) – percentage of image quality. For ‘jpg’, it is a value between 0 and 100. For ‘png’, it is a value between 0 and 9. If not provided, the backend default will be used.

Returns:

json_obj – the serialised json object

Return type:

dict

Variables

mt.opencv.image.PixelFormat

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs

dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs

in the keyword argument list. For example: dict(one=1, two=2)

{'abgr': (9, 4, 1),
 'argb': (10, 4, 1),
 'bgr': (1, 3, 1),
 'bgra': (8, 4, 1),
 'gray': (6, 1, 3),
 'rgb': (0, 3, 1),
 'rgba': (7, 4, 1)}