Image.convolve#

Image.convolve(K: Kernel | ndarray | Any, mode: str = 'same', border: str = 'reflect', bordervalue: int | float = 0) Any[source]#

Image convolution

Parameters:
  • K (Kernel or ndarray, optional) – convolution kernel

  • mode (str, optional) – option for convolution, defaults to ‘same’

  • border (str, optional) – option for boundary handling, defaults to ‘reflect’

  • bordervalue (scalar, optional) – padding value, defaults to 0

Returns:

input image convolved with kernel

Return type:

Image

Computes the convolution of image with the kernel K.

There are two options that control what happens at the edge of the image where the convolution window lies outside the image border. mode controls the size of the resulting image, while border controls how pixel values are extrapolated outside the image border.

mode

description

'same'

output image is same size as input image (default)

'full'

output image is larger than the input image, add border to input image

'valid'

output image is smaller than the input image and contains only valid pixels

border

description

'replicate'

replicate border pixels outwards

'pad'

outside pixels are set to value

'wrap'

borders are joined, left to right, top to bottom

'reflect'

outside pixels reflect inside pixels

'reflect101'

outside pixels reflect inside pixels except for edge

'none'

do not look outside of border

Example:

>>> from machinevisiontoolbox import Image
>>> import numpy as np
>>> img = Image.Read('monalisa.png')
>>> img.convolve(K=np.ones((11,11))).disp()
<matplotlib.image.AxesImage object at 0x7f076e2690a0>

Note

  • The kernel is typically square with an odd side length.

  • The result has the same datatype as the input image. For a kernel where the results could be negative (eg. edge detection kernel) this will cause issues such as value wraparound.

  • If the image is color (has multiple planes) the kernel is applied to each plane, resulting in an output image with the same number of planes.

Warning

treats NaNs in input image or kernels as standard IEEE-754 floating-point values, meaning any convolution operation involving a NaN results in NaN. Because convolution is a sum of products, a single NaN within the kernel’s window propagates to make the output pixel NaN. Use fixbad for handling NaN values.

References:

Important

Uses OpenCV functions cv2.filter2D and cv2.copyMakeBorder which accept multiple-channel, CV_8U, CV_16U, CV_16S, CV_32F or CV_64F images.

Seealso:

Kernel smooth cv2.filter2D cv2.copyMakeBorder fixbad