Image.Random#

classmethod Image.Random(*, size: int | Sequence[int] | None = None, colororder: str | None = None, dtype: Dtype | None = None, maxval: int | float | None = None, pdf: np.ndarray | None = None, like=None) Self[source]#

Create image with random pixel values

Parameters:
  • size (int, 2-tuple or 3-tuple) – image size: size, (width, height) or (width, height, nplanes)

  • colororder (str) – color plane names, defaults to None

  • dtype (str or NumPy dtype, optional) – NumPy datatype, defaults to ‘uint8’

  • maxval (same as dtype, optional) – maximum value for random values, defaults to None

  • pdf (1D or 2D array_like, optional) – probability density function for pixel values, defaults to None

  • like (Image or None, optional) – template image supplying default size, dtype and colororder when those are not given explicitly

Returns:

image of random values

Return type:

Image

The dimensions can be specified by a single scalar, a 2-tuple or a 3-tuple. If a single scalar is given the image is square. If a 2-tuple is given the image has one plane, if a 3-tuple is given the last element specifies the number of planes.

Creates a new image where pixels are initialized to random values:

  • for an integer image the values are uniformly distributed in the range 0 to maxval. If maxval is not given then the values span the range 0 to the maximum positive value of the datatype. For a floating image the values span the range 0.0 to 1.0.

  • if pdf is given then the pixel values are drawn from the given probability density function, which should be normalized to sum to 1. If pdf is a 1D array then the same pdf is used for all planes, if it is a 2D array then each column gives the pdf for the corresponding plane. This option is only supported for uint8 images, and if given then maxval is ignored.

Example:

>>> from machinevisiontoolbox import Image
>>> img = Image.Random(size=3)
>>> img.print()
   196  90 157
     6 164 238
   118 139 241
>>> img = Image.Random(size=3, colororder='RGB')
>>> img.print()
  plane R:
     243  48 119
     201 123 176
      12  26 139
  plane G:
     139 251 242
      77 200 221
     224 194  30
  plane B:
      65  14 124
      34  58  74
      21 224 123
>>> img.red().print()
   243  48 119
   201 123 176
    12  26 139
>>> img = Image.Random(size=3, dtype='float32')
>>> img.print
<bound method Image.print of Image(size=(3, 3), dtype=float32)>
>>> Image.Random(size=100).disp()
<matplotlib.image.AxesImage object at 0x7f076f442ff0>

(Source code, png, hires.png, pdf)

../_images/machinevisiontoolbox-Image-Random-1.png

We could, for example, create a random image with the same histogram as an existing image:

>>> from machinevisiontoolbox import Image
>>> img = Image.Read("street.png")
>>> h = img.hist()
>>> h.plot('pdf')
>>> img2 = Image.Random(size=img.size, pdf=h.pdf)
>>> img2.hist().plot('pdf')

(Source code, png, hires.png, pdf)

../_images/machinevisiontoolbox-Image-Random-2.png
Seealso:

Constant