machinevisiontoolbox.Image.String

classmethod Image.String(s, **kwargs)

Create a small image from text string

Parameters:
  • s (str) – text string

  • kwargs – additional arguments passed to Image constructor

Returns:

image

Return type:

Image

Useful for creating simple images, particularly for unit tests.

Creates a new image initialized to a compact representation given by a string. Two formats are supported:

Single line

Each pixel is a single character in the range 0 to 9, and image rows are separated by a pipe. There are no spaces. All rows must be the same length.

Example:

>>> from machinevisiontoolbox import Image
>>> img = Image.String('01234|56789|87654')
>>> img.print()
 0 1 2 3 4
 5 6 7 8 9
 8 7 6 5 4
Note:

Pixel values are determined by the unicode value of the character relative to unicode for ‘0’, so other ASCII characters (apart from pipe) can be used to obtain pixel values greater than 9. ‘Z’ is 90 and ‘z’ is 122.

Multiline

The string representation of the image is given in ASCII art format:

>>> from machinevisiontoolbox import Image
>>> img = Image.String(r'''
...     ..........
...     .########.
...     .########.
...     .########.
...     .########.
...     ..........
...     ''', binary=True)
>>> img.print()
 0 0 0 0 0 0 0 0 0 0
 0 1 1 1 1 1 1 1 1 0
 0 1 1 1 1 1 1 1 1 0
 0 1 1 1 1 1 1 1 1 0
 0 1 1 1 1 1 1 1 1 0
 0 0 0 0 0 0 0 0 0 0

where the characters represent pixel values: “.” is zero, otherwise the character’s ordinal value is used. Use the binary option to turn 0 and ordinal value into False and True respectively. Indentation is removed, blank lines are ignored. A multi-level image can be created by:

>>> from machinevisiontoolbox import Image
>>> img = Image.String(r'''
...     000000000
...     011112220
...     011112220
...     011112220
...     000000000
...     ''') - ord("0")
>>> img.print()
 0 0 0 0 0 0 0 0 0
 0 1 1 1 1 2 2 2 0
 0 1 1 1 1 2 2 2 0
 0 1 1 1 1 2 2 2 0
 0 0 0 0 0 0 0 0 0

which has pixel values of 0, 1 and 2.

Seealso:

Constant