Image.apply#

Image.apply(func: Callable[..., Any], vectorize: bool = False, **kwargs) Image[source]#

Apply a function to an image

Parameters:
  • func (callable) – function to apply to image or pixel

  • vectorize (bool, optional) – if True apply function to each pixel, defaults to False

  • kwargs – additional keyword arguments to pass to function

Returns:

transformed image

Return type:

Image

If vectorize is False:

  • the function is called with a single argument which is the underlying NumPy array

  • the function must return a NumPy array, which can have different dimensions to its argument. This allows for a large number of NumPy or OpenCV functions to be applied to an image.

  • For a multiplane image the function is called with a 3D array, and can return an array with the same or a different number of channels.

  • the returned NumPy array is encapsulated in a new Image.

If vectorize is True:

  • the function is called for every pixel with a single argument which is a scalar.

  • for a color image the same function is called for each plane with the corresponding pixel value as a scalar.

  • the return array will have the same dimensions (width, height, planes) as its argument.

The function func is called with the image or pixel value as the first argument, followed by any additional keyword arguments.

Example:

>>> from machinevisiontoolbox import Image
>>> import numpy as np
>>> import math
>>> img = Image([[1, 2], [3, 4]])
>>> img.apply(np.sqrt).print()
   1.00 1.41
   1.73 2.00
>>> img.apply(lambda x: math.sqrt(x), vectorize=True).print()
   1.00 1.41
   1.73 2.00

Note

  • Slow when vectorize=True which involves a large number of calls to func.

References:
Seealso:

apply2 numpy.vectorize