Image

class supervisely_lib.imaging.image.CornerAnchorMode[source]

Bases: object

TOP_LEFT = 'tl'
TOP_RIGHT = 'tr'
BOTTOM_LEFT = 'bl'
BOTTOM_RIGHT = 'br'
class supervisely_lib.imaging.image.RotateMode(value)[source]

Bases: enum.Enum

An enumeration.

KEEP_BLACK = 0
CROP_BLACK = 1
SAVE_ORIGINAL_SIZE = 2
supervisely_lib.imaging.image.is_valid_ext(ext: str) → bool[source]

Checks file extension for list of supported images extensions(‘.jpg’, ‘.jpeg’, ‘.mpo’, ‘.bmp’, ‘.png’, ‘.webp’).

Parameters

ext (str) – Image extention.

Returns

True if image extention in list of supported images extensions, False - in otherwise

Return type

bool

Usage example
sly.image.is_valid_ext('.png') # True
sly.image.is_valid_ext('.py') # False
supervisely_lib.imaging.image.has_valid_ext(path: str) → bool[source]

Checks if a given file has a supported extension(‘.jpg’, ‘.jpeg’, ‘.mpo’, ‘.bmp’, ‘.png’, ‘.webp’).

Parameters

path (str) – Path to file.

Returns

True if file extention in list of supported images extensions, False - in otherwise

Return type

bool

Usage example
sly.image.has_valid_ext('/home/admin/work/docs/new_image.jpeg') # True
sly.image.has_valid_ext('/home/admin/work/docs/016_img.py') # False
supervisely_lib.imaging.image.validate_ext(path: str) → None[source]

Generate exception error if file extention is not in list of supported images extensions(‘.jpg’, ‘.jpeg’, ‘.mpo’, ‘.bmp’, ‘.png’, ‘.webp’).

Parameters

path (str) – Path to file.

Returns

None

Return type

NoneType

Usage example
print(sly.image.validate_ext('/home/admin/work/docs/new_image.jpeg'))
# Output: None

try:
    print(sly.image.validate_ext('/home/admin/work/docs/016_img.py'))
except ImageExtensionError as error:
    print(error)

# Output: Unsupported image extension: '.py' for file '/home/admin/work/docs/016_img.py'. Only the following extensions are supported: .jpg, .jpeg, .mpo, .bmp, .png, .webp.
supervisely_lib.imaging.image.validate_format(path: str) → None[source]

Validate input file format, if file extention not supported raise ImageExtensionError.

Parameters

path (str) – Path to file.

Returns

None

Return type

NoneType

Usage example
print(sly.image.validate_format('/home/admin/work/docs/new_image.jpeg'))
# Output: None

try:
    print(sly.image.validate_format('/home/admin/work/docs/016_img.py'))
except ImageReadException as error:
    print(error)

# Output: Error has occured trying to read image '/home/admin/work/docs/016_img.py'. Original exception message: "cannot identify image file '/home/admin/work/docs/016_img.py'"
supervisely_lib.imaging.image.read(path: str, remove_alpha_channel: bool = True) → numpy.ndarray[source]

Loads an image from the specified file and returns it in RGB format.

Parameters
  • path (str) – Path to file.

  • remove_alpha_channel (bool, optional) – Define remove alpha channel when reading file or not.

Returns

Numpy array

Return type

np.ndarray

Usage example
im = sly.image.read('/home/admin/work/docs/image.jpeg')
supervisely_lib.imaging.image.read_bytes(image_bytes: str, keep_alpha: bool = False) → numpy.ndarray[source]

Loads an byte image and returns it in RGB format.

Parameters
  • image_bytes (str) – Path to file.

  • keep_alpha (bool, optional) – Define consider alpha channel when reading bytes or not.

Returns

Numpy array

Return type

np.ndarray

Usage example
im_bytes = 'ÿØÿàJFIF\...Ù'
im = sly.image.read_bytes(im_bytes)
supervisely_lib.imaging.image.write(path: str, img: numpy.ndarray, remove_alpha_channel: bool = True) → None[source]

Saves the image to the specified file. It create directory from path if the directory for this path does not exist.

Parameters
  • path (str) – Path to file.

  • img (np.ndarray) – Image in numpy array(RGB format).

  • remove_alpha_channel (bool, optional) – Define remove alpha channel when writing file or not.

Returns

None

Return type

NoneType

Usage example
path = '/home/admin/work/docs/new_image.jpeg'
sly.image.write(path, image_np)
supervisely_lib.imaging.image.draw_text_sequence(bitmap: numpy.ndarray, texts: List[str], anchor_point: Tuple[int, int], corner_snap: supervisely_lib.imaging.image.CornerAnchorMode = 'tl', col_space: int = 12, font: Optional[PIL.ImageFont.FreeTypeFont] = None, fill_background: bool = True) → None[source]

Draws text labels on bitmap from left to right with col_space spacing between labels.

Parameters
  • bitmap (np.ndarray) – Image to draw texts in numpy format.

  • texts (List[str]) – List of texts to draw on image.

  • anchor_point (Tuple[int, int]) – Coordinates of the place on the image where the text will be displayed(row, column).

  • corner_snap (CornerAnchorMode, optional) – Corner of image to draw texts.

  • col_space (int, optional) – Distance between texts.

  • font (ImageFont.FreeTypeFont, optional) – Type of text font.

  • fill_background (bool, optional) – Define fill text background or not.

Returns

None

Return type

NoneType

Usage example
sly.image.draw_text_sequence(image, ['some_text', 'another_text'], (10, 10))
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/wIzrDuf.jpg

After

supervisely_lib.imaging.image.draw_text(bitmap: numpy.ndarray, text: str, anchor_point: Tuple[int, int], corner_snap: supervisely_lib.imaging.image.CornerAnchorMode = 'tl', font: Optional[PIL.ImageFont.FreeTypeFont] = None, fill_background=True) → Tuple[int, int][source]

Draws given text on bitmap image.

Parameters
  • bitmap (np.ndarray) – Image to draw texts in numpy format.

  • texts (str) – Text to draw on image.

  • anchor_point (Tuple[int, int]) – Coordinates of the place on the image where the text will be displayed(row, column).

  • corner_snap (CornerAnchorMode, optional) – Corner of image to draw texts.

  • font (ImageFont.FreeTypeFont, optional) – Type of text font.

  • fill_background (bool, optional) – Define fill text background or not.

Returns

Height and width of text

Return type

Tuple[int, int]

Usage example
sly.image.draw_text(image, 'your text', (100, 50))
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/6Ptz8Tf.jpg

After

supervisely_lib.imaging.image.write_bytes(img: numpy.ndarray, ext: str) → bytes[source]

Compresses the image and stores it in the byte object.

Parameters
  • img (np.ndarray) – Image in numpy format(RGB).

  • ext (str) – File extension that defines the output format.

Returns

Bytes object

Return type

bytes

Usage example
bytes = sly.image.write_bytes(image_np, 'jpeg')
print(type(bytes))
# Output: <class 'bytes'>
supervisely_lib.imaging.image.get_hash(img: numpy.ndarray, ext: str) → str[source]

Hash input image with sha256 algoritm and encode result by using Base64.

Parameters
  • img (np.ndarray) – Image in numpy format(RGB).

  • ext (str) – File extension that defines the output format.

Returns

Hash string

Return type

str

Usage example
hash = sly.image.get_hash(im, 'jpeg')
print(hash)
# Output: fTec3RD7Zxg0aYc0ooa5phPfBrzDe01urlFsgi5IzIQ=
supervisely_lib.imaging.image.crop(img: numpy.ndarray, rect: supervisely_lib.geometry.rectangle.Rectangle) → numpy.ndarray[source]

Crop part of the image with rectangle size. If rectangle for crop is out of image area it generates ValueError.

Parameters
  • img (np.ndarray) – Image in numpy format(RGB).

  • rect (Rectangle) – Rectangle object for crop.

Returns

Cropped image in numpy format

Return type

np.ndarray

Usage example
# If size of rectangle is more then image shape raise ValueError:
try:
    crop_image = sly.image.crop(image_np, sly.Rectangle(0, 0, 5000, 6000))
except ValueError as error:
    print(error)
# Output: Rectangle for crop out of image area!

crop_im = sly.image.crop(image_np, sly.Rectangle(0, 0, 500, 600))
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/4tNm2GS.jpg

After

supervisely_lib.imaging.image.crop_with_padding(img: numpy.ndarray, rect: supervisely_lib.geometry.rectangle.Rectangle) → numpy.ndarray[source]

Crop part of the image with rectangle size. If rectangle for crop is out of image area it generates additional padding.

Parameters
  • img (np.ndarray) – Image in numpy format(RGB).

  • rect (Rectangle) – Rectangle object for crop.

Returns

Cropped image in numpy format

Return type

np.ndarray

Usage example
crop_with_padding_image = sly.image.crop_with_padding(image_np, sly.Rectangle(0, 0, 1000, 1200))
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/Nv1UinH.jpg

After

supervisely_lib.imaging.image.restore_proportional_size(in_size: Tuple[int, int], out_size: Optional[Tuple[int, int]] = None, frow: Optional[float] = None, fcol: Optional[float] = None, f: Optional[float] = None) → Tuple[int, int][source]

Calculate new size of the image.

Parameters
  • in_size (Tuple[int, int]) – Size of input image (height, width).

  • out_size (Tuple[int, int], optional) – New image size (height, width).

  • frow (float, optional) – Length of output image.

  • fcol (float, optional) – Height of output image.

  • f (float, optional) – Positive non zero scale factor.

Returns

Height and width of image

Return type

Tuple[int, int]

supervisely_lib.imaging.image.resize(img: numpy.ndarray, out_size: Optional[Tuple[int, int]] = None, frow: Optional[float] = None, fcol: Optional[float] = None) → numpy.ndarray[source]

Resize the image to the specified size.

Parameters
  • img (np.ndarray) – Image in numpy format(RGB).

  • out_size (Tuple[int, int], optional) – New image size (height, width).

  • frow (float, optional) – Length of output image.

  • fcol (float, optional) – Height of output image.

Returns

Resize image in numpy format

Return type

np.ndarray

Usage example
resize_image = sly.image.resize(image_np, (300, 500))
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/Xya4yz0.jpg

After

supervisely_lib.imaging.image.resize_inter_nearest(img: numpy.ndarray, out_size: Optional[tuple] = None, frow: Optional[float] = None, fcol: Optional[float] = None) → numpy.ndarray[source]

Resize image to match a certain size. Performs interpolation to up-size or down-size images.

Parameters
  • img (np.ndarray) – Image in numpy format(RGB).

  • out_size (Tuple[int, int], optional) – New image size (height, width).

  • frow (float, optional) – Length of output image.

  • fcol (float, optional) – Height of output image.

Returns

Resize image in numpy format

Return type

np.ndarray

Usage example
resize_image_nearest = sly.image.resize_inter_nearest(image_np, (300, 700))
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/0O6yMDH.jpg

After

supervisely_lib.imaging.image.scale(img: numpy.ndarray, factor: float) → numpy.ndarray[source]

Scales current image with the given factor.

Parameters
  • img (np.ndarray) – Image in numpy format(RGB).

  • factor (float) – Scale size.

Returns

Resize image in numpy format

Return type

np.ndarray

Usage example
scale_image = sly.image.scale(image_np, 0.3)
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/NyP8tts.jpg

After

supervisely_lib.imaging.image.fliplr(img: numpy.ndarray) → numpy.ndarray[source]

Flips the current image horizontally.

Parameters

img (np.ndarray) – Image in numpy format(RGB).

Returns

Flip image in numpy format

Return type

np.ndarray

Usage example
fliplr_image = sly.image.fliplr(image_np)
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/1mqnuZU.jpg

After

supervisely_lib.imaging.image.flipud(img: numpy.ndarray) → numpy.ndarray[source]

Flips the current image vertically.

Parameters

img (np.ndarray) – Image in numpy format(RGB).

Returns

Flip image in numpy format

Return type

np.ndarray

Usage example
flipud_image = sly.image.flipud(image_np)
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/LDwRDvm.jpg

After

supervisely_lib.imaging.image.rotate(img: numpy.ndarray, degrees_angle: int, mode=<RotateMode.KEEP_BLACK: 0>) → numpy.ndarray[source]

Rotates current image.

Parameters
  • img (np.ndarray) – Image in numpy format(RGB).

  • degrees_angle (int) – Angle in degrees for rotating.

  • mode (RotateMode, optional) – One of RotateMode enum values.

Returns

Rotate image in numpy format

Return type

np.ndarray

Usage example
from supervisely_lib.imaging.image import RotateMode
# keep_black mode
rotate_im_keep_black = sly.image.rotate(image_np, 45)
# crop_black mode
rotate_im_crop_black = sly.image.rotate(image_np, 45, RotateMode.CROP_BLACK)
# origin_size mode
rotate_im_origin_size = sly.image.rotate(image_np, 45, RotateMode.SAVE_ORIGINAL_SIZE) * 255
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/VjiwV4O.jpg

After keep_black mode

https://i.imgur.com/Rs34eMa.jpg

After crop_black mode

https://i.imgur.com/ttDWfBE.jpg

After origin_size mode

supervisely_lib.imaging.image.random_contrast(image: numpy.ndarray, min_factor: float, max_factor: float) → numpy.ndarray[source]

Randomly changes contrast of the input image.

Parameters
  • image (np.ndarray) – Image in numpy format(RGB).

  • min_factor (float) – Lower bound of contrast range.

  • max_factor (float) – Upper bound of contrast range.

Returns

Image in numpy format with new contrast

Return type

np.ndarray

Usage example
rand_contrast_im = sly.image.random_contrast(image_np, 1.1, 1.8)
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/4zSNuJU.jpg

After

supervisely_lib.imaging.image.random_brightness(image: numpy.ndarray, min_factor: float, max_factor: float) → numpy.ndarray[source]

Randomly changes brightness of the input image.

Parameters
  • image (np.ndarray) – Image in numpy format(RGB).

  • min_factor (float) – Lower bound of brightness range.

  • max_factor (float) – Upper bound of brightness range.

Returns

Image in numpy format with new brightness

Return type

np.ndarray

Usage example
rand_brightness_im = sly.image.random_brightness(image_np, 1.5, 8.5)
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/bOYwwYH.jpg

After

supervisely_lib.imaging.image.random_noise(image: numpy.ndarray, mean: float, std: float) → numpy.ndarray[source]

Adds random Gaussian noise to the input image.

Parameters
  • image (np.ndarray) – Image in numpy format(RGB).

  • mean (float) – The mean value of noise distribution.

  • std (float) – The standard deviation of noise distribution.

Returns

Image in numpy format with random noise

Return type

np.ndarray

Usage example
random_noise_im = sly.image.random_noise(image_np, 25, 19)
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/EzyEHeM.jpg

After

supervisely_lib.imaging.image.random_color_scale(image: numpy.ndarray, min_factor: float, max_factor: float) → numpy.ndarray[source]

Changes image colors by randomly scaling each of RGB components. The scaling factors are sampled uniformly from the given range.

Parameters
  • image (np.ndarray) – Image in numpy format(RGB).

  • min_factor (float) – Minimum scale factor.

  • max_factor (float) – Maximum scale factor.

Returns

Image in numpy format with random color scale

Return type

np.ndarray

Usage example
random_color_scale_im = sly.image.random_color_scale(image_np, 0.5, 0.9)
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/GGUZqlA.jpg

After

supervisely_lib.imaging.image.blur(image: numpy.ndarray, kernel_size: int) → numpy.ndarray[source]

Blurs an image using the normalized box filter.

Parameters
  • image (np.ndarray) – Image in numpy format(RGB).

  • kernel_size (int) – Blurring kernel size.

Returns

Image in numpy format with blur

Return type

np.ndarray

Usage example
blur_im = sly.image.blur(image_np, 7)
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/wFnBaC6.jpg

After

supervisely_lib.imaging.image.median_blur(image: numpy.ndarray, kernel_size: int) → numpy.ndarray[source]

Blurs an image using the median filter.

Parameters
  • image (np.ndarray) – Image in numpy format(RGB).

  • kernel_size (int) – Blurring kernel size(must be odd and greater than 1, for example: 3, 5, 7).

Returns

Image in numpy format with median blur

Return type

np.ndarray

Usage example
median_blur_im = sly.image.median_blur(image_np, 5)
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/FQ977ON.jpg

After

supervisely_lib.imaging.image.gaussian_blur(image: numpy.ndarray, sigma_min: float, sigma_max: float) → numpy.ndarray[source]

Blurs an image using a Gaussian filter.

Parameters
  • image (np.ndarray) – Image in numpy format(RGB).

  • sigma_min (float) – Lower bound of Gaussian kernel standard deviation range.

  • sigma_min – Upper bound of Gaussian kernel standard deviation range.

Returns

Image in numpy format with gaussian blur

Return type

np.ndarray

Usage example
gaussian_blur_im = sly.image.gaussian_blur(image_np, 3.3, 7.5)
https://i.imgur.com/BHUALdv.jpg

Before

https://i.imgur.com/brs6Au0.jpg

After

supervisely_lib.imaging.image.drop_image_alpha_channel(img: numpy.ndarray) → numpy.ndarray[source]

Converts 4-channel image to 3-channel.

Parameters

img (np.ndarray) – Image in numpy format(RGBA).

Returns

Image in numpy format(RGB)

Return type

np.ndarray

supervisely_lib.imaging.image.np_image_to_data_url(img: numpy.ndarray) → str[source]

Convert image to url string.

Parameters

img (np.ndarray) – Image in numpy format(RGBA or RGB).

Returns

String with image url

Return type

str

Usage example
data_url = sly.image.np_image_to_data_url(im)
print(data_url)
# Output: 'data:image/png;base64,iVBORw0K...'
supervisely_lib.imaging.image.data_url_to_numpy(data_url: str) → numpy.ndarray[source]

Convert url string to numpy image(RGB).

Parameters

img (str) – String with image url.

Returns

Image in numpy format(RGBA)

Return type

np.ndarray

Usage example
image_np = sly.image.data_url_to_numpy(data_url)
supervisely_lib.imaging.image.np_image_to_data_url_backup_rgb(img: numpy.ndarray) → str[source]

Convert image to url string.

Parameters

img (np.ndarray) – Image in numpy format(only RGB).

Returns

String with image url

Return type

str

Usage example
data_url = sly.image.np_image_to_data_url_backup_rgb(im)
print(data_url)
# Output: 'data:image/png;base64,iVBORw0K...'