scistag.imagestag.image.Image¶
- class Image(source=None, framework=None, pixel_format=None, size=None, bg_color=None, **params)[source]¶
Bases:
ImageBaseSciStag’s default class for storing image data in all common pixel formats.
The data is internally either stored using the PILLOW image library’s Image class or as a classical numpy array, depending on how it was initialized. If not specified otherwise it will always the PILLOW representation as this is very well suited to visualize the data or modify it using the Canvas class.
If you want to access the data directly you can at all times call the to_pil or get_pixels function.
Usage example:
""" Simple demo which loads an image from the web using WebStag, loads it via ImageStag and displays it in a TKInter window. """ import tkinter from PIL import ImageTk from scistag.imagestag import Image from scistag.tests import TestConstants from scistag.webstag import web_fetch def main(): root = tkinter.Tk() # fetch data from web url = TestConstants.STAG_URL print(f"Loading image from {url}...") image_data = web_fetch(url) # create an image image = Image(image_data) # display it img = ImageTk.PhotoImage(image.to_pil()) panel = tkinter.Label(root, image=img) panel.pack(side="bottom", fill="both", expand="yes") # run the main loop root.mainloop() if __name__ == "__main__": main()
- Parameters
source (ImageSourceTypes | None) –
The image source. Either a file name, a http URL, numpy array or one of the supported low level types. Note that the pixel source you refer, e.g. a PIl image or a numpy array might be referenced directly and modified by this object.
Files from the web are cached by default if not disabled otherwise via cache=False using WebStag’s default caching duration and size.
framework (ImsFramework) – The framework to be used if the file is loaded from disk
pixel_format (PixelFormat | None) – The pixel format - if the data was passed as np.array. RGB by default.
size (Size2DTypes | None) – The size of the new image (if no source ia passed)
bg_color (Color | None) – The background color of the new image
params – Source protocol dependent, additional loading parameters
Raises a ValueError if the image could not be loaded
Methods
Converts BGR to RGB or the otherwise round
Computes the new size of an image after rescaling with a given maximum width and/or height and a given original size.
Converts the image's format
Converts the image to use the RAW framework which is faster if you excessively access the pixel data frequently.
Converts the image to use the RAW framework which is faster if you excessively access the pixel data frequently.
Creates a copy of this image.
Crops a region of the image and returns it
Detects the format
Compresses the image and returns the compressed file's data as bytes object.
Creates an image from a "classic" bgr, bgra or grayscale OpenCV source.
Returns the names of the single color bands
Returns the low level data handle, for example a numpy array or a PIL handle.
Returns an image uniquely identifying it
Returns the image's pixel data as
np.ndarray.Returns the pixels and ensures they are either bgr or bgra
Returns the pixels and ensures they are gray scale
Returns the pixels and ensures they are either rgb or rgba
Returns the image's raw pixel data as flattened byte array
Returns the image's size in pixels
Returns the image's size
Returns if the current format is bgr or bgra
Returns if the image is transparent, either alpha transparent or color keyed.
Guarantees that the output will be in the BGR or BGRA format
Guarantees that the output will be grayscale
Guarantees that the output will be in the RGB or RGBA format
Resizes the image to given resolution (modifying this image directly)
Returns an image resized to given resolution
Returns a resized variant of the image with many configuration possibilities.
Saves the image to disk
Returns the single bands as single channels.
Converts the image to ASCII, e.g.
Converts the image to a canvas (if possible)
Converts the pixel data from the current format to it's counter type in OpenCV
Converts the image to it's IPython representation, e.g. to allow
Encodes the image as jpeg.
Converts the image to a PIL image object
Encodes the image as png.
Attributes
__array_interface__Conversion to numpy representation
__dict____doc____module____weakref__list of weak references to the object (if defined)
Returns the image's size in pixels
The image's width in pixels
The image's height in pixels
The framework being used.
The PILLOW handle (if available)
The pixel data (if available) as numpy array
The base format (rgb, rbga, bgr etc.)
- _init_as_cv2(source)[source]¶
Initializes the image from a numpy array and assuming OpenCV’s BGR / BGRA color channel order
- Parameters
source (
ndarray) – The data source
- _init_as_pil(source)[source]¶
Initializes the image as PIL image
- Parameters
source – The data source
- classmethod _pixel_data_from_source(source)¶
Loads an arbitrary source and returns it as pixel data
- classmethod _prepare_data_source(framework, source, pixel_format, **params)[source]¶
Prepares and if necessary converts the data source to a supported format
- Parameters
framework (
ImsFramework) – The framework being usedsource (
Union[str,ndarray,bytes,Image,type]) – The source, a byte steam, a filename or a http URLparams – Source protocol dependent, additional loading parameters
- Returns
The prepared source data
- static bgr_to_rgb(pixel_data)¶
Converts BGR to RGB or the otherwise round
- Parameters
pixel_data (
ndarray) – The input pixel data- Return type
ndarray- Returns
The output pixel data
- compute_rescaled_size_from_max_size(max_size, org_size)[source]¶
Computes the new size of an image after rescaling with a given maximum width and/or height and a given original size.
- convert(target_format, bg_fill=None)[source]¶
Converts the image’s format
- Parameters
target_format (PixelFormat | str) – The target format
bg_fill (Union['Color', None]) – For alpha-transparent images only: The color of the background of the new non-transparent image.
- Return type
- Returns
Self
- convert_to_pil()[source]¶
Converts the image to use the RAW framework which is faster if you excessively access the pixel data frequently.
- Return type
- convert_to_raw()[source]¶
Converts the image to use the RAW framework which is faster if you excessively access the pixel data frequently.
- Return type
- copy()[source]¶
Creates a copy of this image.
By default a PILLOW based image will be created
- Return type
- Returns
A copy of this image
- cropped(box)[source]¶
Crops a region of the image and returns it
- Parameters
box (
Union[Bounding2D,tuple[int,int,int,int],tuple[float,float,float,float],tuple[Union[Pos2D,tuple[float,float]],Union[Pos2D,tuple[float,float]]],tuple[Union[Pos2D,tuple[float,float]],Union[tuple[float,float],Size2D]]]) – The box in the form x, y, x2, y2- Return type
- Returns
The image of the defined subregion
- classmethod detect_format(pixels, is_cv2=False)¶
Detects the format
- Parameters
pixels (
ndarray) – The pixelsis_cv2 – Defines if the source was OpenCV
- Returns
The pixel format. See PixelFormat
- encode(filetype='png', quality=90, background_color=None)[source]¶
Compresses the image and returns the compressed file’s data as bytes object.
- Parameters
filetype (str | tuple[str, int]) –
The output file type. Valid types are “png”, “jpg”/”jpeg”, “bmp” and “gif”.
You can also pass the filetype and quality as a str, int tuple such as(“jpg”, 60).
quality (int) – The image quality between (0 = worst quality) and (95 = best quality). >95 = minimal loss
background_color (Color | None) – The background color to store an RGBA image as RGB image.
- Return type
bytes | None
- Returns
The bytes object if no error occurred, otherwise None
- classmethod from_cv2(pixel_data)¶
Creates an image from a “classic” bgr, bgra or grayscale OpenCV source.
For more advanced type please use the standard constructor.
- Parameters
pixel_data (
ndarray) – The pixel data- Return type
- Returns
The image instance
- get_handle()[source]¶
Returns the low level data handle, for example a numpy array or a PIL handle.
Do not use this to modify the data and be aware of the the type could change dynamically. Use method:~get_pixels or :method:`~to_pil` if you need a guaranteed type.
- Return type
np.ndarray | PIL.Image.Image
- Returns
The handle
- get_pixels(desired_format=None)[source]¶
Returns the image’s pixel data as
np.ndarray.Note that manipulating the data will has no effect to the image if the internal representation is not a numpy array.
- Parameters
desired_format (PixelFormat | None) – The desired output pixel format, e.g. see
PixelFormat. By default the own format- Return type
np.ndarray
- Returns
The numpy array containing the pixels
- get_pixels_bgr()[source]¶
Returns the pixels and ensures they are either bgr or bgra
- Return type
ndarray
- get_pixels_rgb()[source]¶
Returns the pixels and ensures they are either rgb or rgba
- Return type
ndarray
- get_raw_data()[source]¶
Returns the image’s raw pixel data as flattened byte array
- Return type
- Returns
The image’s pixel data
- is_bgr()[source]¶
Returns if the current format is bgr or bgra
- Return type
- Returns
True if the image currently in bgr or bgra format
- is_transparent()[source]¶
Returns if the image is transparent, either alpha transparent or color keyed.
- Return type
- Returns
True if the image is transparent
- classmethod normalize_to_bgr(pixels, input_format=PixelFormat.RGB, keep_gray=False)¶
Guarantees that the output will be in the BGR or BGRA format
- Parameters
pixels (
ndarray) – The pixel datainput_format (
PixelFormat) – The input format representation, e.g. seePixelFormatkeep_gray – Defines if single channel formats shall be kept intact. False by default.
- Return type
ndarray- Returns
The BGR image as numpy array. If keep_gray was set and the input was single channeled the original.
- classmethod normalize_to_gray(pixels, input_format=PixelFormat.RGB)¶
Guarantees that the output will be grayscale
- Parameters
pixels (
ndarray) – The pixel datanp.ndarrayinput_format (
PixelFormat) – The input format representation, e.g. seePixelFormat
- Return type
ndarray- Returns
The grayscale image as
np.ndarray
- classmethod normalize_to_rgb(pixels, input_format=<enum 'PixelFormat'>, keep_gray=False)¶
Guarantees that the output will be in the RGB or RGBA format
- Parameters
pixels (
ndarray) – The pixel data asnp.ndarrayinput_format (
PixelFormat) – The input format representation, e.g. seePixelFormatkeep_gray – Defines if single channel formats shall be kept intact. False by default.
- Return type
ndarray- Returns
The RGB image as numpy array. If keep_gray was set and the input was single channeled the original.
- resize(size, interpolation=InterpolationMethod.LANCZOS)[source]¶
Resizes the image to given resolution (modifying this image directly)
- resized(size, interpolation=InterpolationMethod.LANCZOS)[source]¶
Returns an image resized to given resolution
- resized_ext(size=None, max_size=None, keep_aspect=False, target_aspect=None, fill_area=False, factor=None, interpolation=InterpolationMethod.LANCZOS, background_color=Color(r=0.0, g=0.0, b=0.0, a=1.0, _rgba=(0.0, 0.0, 0.0, 1.0), _int_rgba=(0, 0, 0, 255)))[source]¶
Returns a resized variant of the image with many configuration possibilities.
- Parameters
size (Size2DTypes | None) – The target size as tuple (in pixels) (optional)
max_size (Size2DTypes | tuple[int | None, int | None] | None) – The maximum width and/or height to which the image shall be scaled while keeping the aspect_ration intact. You can pass a maximum width, a maximum height or both.
keep_aspect (bool) – Defines if the aspect ratio shall be kept. if set to true the image will be zoomed or shrunk equally on both axis so it fits the target size. False by default.
target_aspect (float | None) –
If defined the image will be forced into given aspect ratio by adding “black bars” (or the color you defined in “background_color”). Common values are for example 4/3, 16/9 or 21/9.
Note that this does NOT change the aspect ratio of the real image itself. If you want to change this just call this function with the desired “size” parameter.
It will always preserve the size of the axis to which no black bares are added, so e.g. converting an image from 4:3 to 16:9 resulting in black bars on left and right side the original height will be kept.
Converting an image from 16:9 to 4:3 on the other hand where black bars are added on top and bottom the width will be kept. Overrides “size”.
fill_area (bool) –
Defines if the whole area shall be filled with the original image.
False by default. Only evaluated if keep_aspect is True as well as otherwise a simple definition of “size” would anyway do the job.
factor (float | tuple[float, float] | None) –
Scales the image by given factor. Overwrites size.
Can be combined with target_aspect. None by default. Overrides “size”.
interpolation (InterpolationMethod) – The interpolation method.
background_color – The color which shall be used to fill the empty area, e.g. when a certain aspect ratio is enforced.
- Return type
- split()[source]¶
Returns the single bands as single channels.
In difference to
get_pixels()the data is reshaped to channel x height x width so each channel can be handled separately.Single band channels (such as gray) also guarantee a three dimensional shape. (1 x Height x Width)
- Return type
list[ndarray]- Returns
The single channels.
- to_ascii(max_width=80, **params)[source]¶
Converts the image to ASCII, e.g. to add a coarse preview to a log file… or just 4 fun ;-).
- Parameters
max_width – The maximum count of characters per row
- Return type
- Returns
The ASCII image as string
- to_canvas()[source]¶
Converts the image to a canvas (if possible)
- Return type
- Returns
The canvas handle
- to_cv2()[source]¶
Converts the pixel data from the current format to it’s counter type in OpenCV
- Return type
ndarray- Returns
The OpenCV numpy data
- to_ipython(filetype='png', quality=90, **params)[source]¶
- Converts the image to it’s IPython representation, e.g. to allow
faster visualization via using JPG.
- framework¶
The framework being used. ImsFramework.PIL by default.
- height¶
The image’s height in pixels
- pixel_format: PixelFormat¶
The base format (rgb, rbga, bgr etc.)
- width¶
The image’s width in pixels