Image container#
- class kornia.image.ImageSize(height, width)[source]#
Hold the height and width of an image, without its channels.
size = ImageSize(height, width)stores the two sizes of one image in a frozen data class, read back assize.heightandsize.width. The positional order is(height, width), kornia’s order for sizes and the reverse of \((x, y)\) points.- Parameters:
See also
ImageLayout: holds anImageSizetogether with the channel count and order.Image: checks the size against the shape of its data.
Example
>>> size = ImageSize(3, 4) >>> size.height 3 >>> size.width 4
- class kornia.image.PixelFormat(color_space, bit_depth)[source]#
Hold the color space of an image and the storage size of one channel value.
pixel_format = PixelFormat(color_space, bit_depth)describes the values of anImage: theirColorSpaceand the bits that store one channel value. The data class checks nothing;Imageraises when either field does not fit its data.- Parameters:
color_space (
ColorSpace) – color space.bit_depth (
int) – the storage size of one channel value in bits,8 * element_size()of the data: 8 foruint8, 32 forfloat32.
See also
ColorSpace: the values ofcolor_space.ImageLayout: describes the arrangement of the values instead: size, channel count and order.
Example
>>> pixel_format = PixelFormat(ColorSpace.RGB, 8) >>> pixel_format.color_space <ColorSpace.RGB: 2> >>> pixel_format.bit_depth 8
-
color_space:
ColorSpace#
- class kornia.image.ColorSpace(value)[source]#
Name the color space of an image: unknown, gray, RGB or BGR.
ColorSpace.RGBand its siblings label the channels of anImagethroughPixelFormat.Imagechecks the label against the channel count:GRAYneeds 1 channel,RGBandBGRneed 3, andUNKNOWNtakes any count. No member has alpha, so a 4-channel image isUNKNOWN.See also
PixelFormat: pairs the color space with the bit depth.Image: converts betweenGRAY,RGBandBGRwithto_gray,to_rgbandto_bgr.
- BGR = 3#
- GRAY = 1#
- RGB = 2#
- UNKNOWN = 0#
- class kornia.image.ChannelsOrder(value)[source]#
Name where an image keeps its channels: first,
(C, H, W), or last,(H, W, C).ChannelsOrder.CHANNELS_FIRSTis the order of kornia tensors,(C, H, W), andCHANNELS_LASTthe order of NumPy and OpenCV arrays,(H, W, C).ImageLayoutcarries it, andImagechecks the shape of its data against it.See also
ImageLayout: holds the order together with the size and the channel count.
- CHANNELS_FIRST = 0#
- CHANNELS_LAST = 1#
- class kornia.image.ImageLayout(image_size, channels, channels_order)[source]#
Hold the size, channel count and channel order of an image.
layout = ImageLayout(ImageSize(H, W), C, ChannelsOrder.CHANNELS_FIRST)describes the shape of anImage’s data. The data class checks nothing;ImageraisesShapeErrorwhen its data does not have this shape.- Parameters:
image_size (
ImageSize) – image size.channels (
int) – number of channels.channels_order (
ChannelsOrder) – channels order.
See also
ImageSize: theimage_sizefield.ChannelsOrder: thechannels_orderfield.PixelFormat: describes the values of the pixels instead of their arrangement.
Example
>>> layout = ImageLayout(ImageSize(3, 4), 3, ChannelsOrder.CHANNELS_LAST) >>> layout.image_size ImageSize(height=3, width=4) >>> layout.channels 3 >>> layout.channels_order <ChannelsOrder.CHANNELS_LAST: 1>
-
channels_order:
ChannelsOrder#
- class kornia.image.Image(data, pixel_format, layout)[source]#
Hold one image tensor with its layout and color space, checked against the data.
img = Image(data, pixel_format, layout)wraps one unbatched image tensor,(C, H, W)or(H, W, C)aslayout.channels_ordersays, and raises when the shape, the bit depth or the color space does not fit the data.from_numpy(),from_dlpack()andfrom_file()build the layout and the pixel format for you. kornia’s other functions take plain channels-first tensors: pass themimg.dataof aCHANNELS_FIRSTimage, orimg.data[None]where they take a batch.Warning
This API is experimental and might suffer changes in the future.
- Convention:
A batch or an
(H, W)tensor raisesShapeError.from_numpy(),to_numpy(),from_dlpack()andto_dlpack()share memory with the array or capsule of a CPU image, except thatto_numpy()copies bfloat16 data to float32 because NumPy has no bfloat16 dtype.to_numpy()andto_dlpack()return the stored layout, so an image fromfrom_file()gives(C, H, W). Neither the array nor the capsule carries the layout or the color space:from_numpy()reads(H, W, C)andfrom_dlpack()reads(C, H, W)unlesschannels_ordersays otherwise, and both label the color space by channel count unlesscolor_spaceis given. Passimg.pixel_format.color_spaceandimg.channels_orderto read an exported image back.to_gray(),to_rgb()andto_bgr()return the image itself when it is already in that color space, an image with new data when it is in another of the three, and raiseValueErrorforUNKNOWN. Converting RGB or BGR to gray requiresuint8or a floating dtype supported byrgb_to_grayscale(); other integer dtypes, such asuint16, raiseTypeErroreven thoughImagecan hold them.to(),float()andclone()return a newImageand leave this one unchanged.
- Parameters:
data (
Tensor) – a torch.Tensor containing the image data.pixel_format (
PixelFormat) – the pixel format of the image.layout (
ImageLayout) – a dataclass containing the image layout information.
See also
load_image(): loads a file as a plain tensor, with a choice ofImageLoadType;from_file()always loadsRGB8.image_to_tensor(): converts a NumPy array to a channels-first tensor without the container.ImageLayout: the shape description the constructor checks.PixelFormat: the value description the constructor checks.
Examples
>>> # from a torch.tensor >>> data = torch.randint(0, 255, (3, 4, 5), dtype=torch.uint8) # CxHxW >>> pixel_format = PixelFormat( ... color_space=ColorSpace.RGB, ... bit_depth=8, ... ) >>> layout = ImageLayout( ... image_size=ImageSize(4, 5), ... channels=3, ... channels_order=ChannelsOrder.CHANNELS_FIRST, ... ) >>> img = Image(data, pixel_format, layout) >>> assert img.channels == 3
>>> # from a numpy array (like opencv) >>> data = np.ones((4, 5, 3), dtype=np.uint8) # HxWxC >>> img = Image.from_numpy(data, color_space=ColorSpace.RGB) >>> assert img.channels == 3 >>> assert img.width == 5 >>> assert img.height == 4
- property channels_order: ChannelsOrder#
Return the channels order.
- float()[source]#
Return the image as float32 without rescaling; the image itself is not changed.
A
uint8255 becomes 255.0, outside the \([0, 1]\) range thatprint()reads for a float image.- Return type:
- classmethod from_dlpack(data, color_space=None, channels_order=ChannelsOrder.CHANNELS_FIRST)[source]#
Construct an
Imagefrom a DLPack capsule, sharing its memory.A capsule carries neither the layout nor the color space, so read
img.to_dlpack()back withImage.from_dlpack(capsule, img.pixel_format.color_space, img.channels_order).- Parameters:
data (
Any) – a DLPack capsule from numpy, tvm or jax, holding a(C, H, W)image, or(H, W, C)withchannels_order=CHANNELS_LAST.color_space (
Optional[ColorSpace], optional) – the color space of the image. IfNone, a 1-channel image isGRAY, a 3-channel image isRGBand any other channel count isUNKNOWN. An explicit color space that does not match the channel count raises. Default:Nonechannels_order (
ChannelsOrder, optional) – the layout of the capsule. Default:ChannelsOrder.CHANNELS_FIRST
- Raises:
ValueError – if
channels_orderis neitherCHANNELS_LASTnorCHANNELS_FIRST.ValueCheckError – if an explicit
color_spacedoes not match the channel count (also aValueError).ShapeError – if the capsule has more than three dimensions. It is also a
ValueError.IndexError – if the capsule has fewer than three dimensions.
- Return type:
Example
>>> x = np.ones((3, 4, 5)) # (C, H, W) >>> img = Image.from_dlpack(x.__dlpack__()) >>> img.channels, img.height, img.width (3, 4, 5) >>> hwc = Image.from_numpy(np.ones((4, 5, 3), dtype=np.uint8)) # (H, W, C), CHANNELS_LAST >>> back = Image.from_dlpack(hwc.to_dlpack(), hwc.pixel_format.color_space, hwc.channels_order) >>> back.channels, back.height, back.width (3, 4, 5)
- classmethod from_file(file_path)[source]#
Construct an
Imagefrom a file.The file is loaded with
load_image()asImageLoadType.RGB8: the image is(3, H, W)uint8,RGBandCHANNELS_FIRST, on the CPU.
- classmethod from_numpy(data, color_space=None, channels_order=ChannelsOrder.CHANNELS_LAST)[source]#
Construct an
Imagefrom a numpy array, sharing its memory.- Parameters:
data (
Any) – a numpy array containing the image data.color_space (
Optional[ColorSpace], optional) – the color space of the image. IfNone, a 1-channel array isGRAY, a 3-channel array isRGBand any other channel count isUNKNOWN. An explicit color space that does not match the channel count raises. Default:Nonechannels_order (
ChannelsOrder, optional) – what dimension the channels are in the image torch.Tensor. Default:ChannelsOrder.CHANNELS_LAST
- Raises:
ValueError – if
channels_orderis neitherCHANNELS_LASTnorCHANNELS_FIRST.ValueCheckError – if an explicit
color_spacedoes not match the channel count (also aValueError).ShapeError – if
datahas more than three dimensions. It is also aValueError.IndexError – if
datahas fewer than two dimensions.
- Return type:
Example
>>> data = np.ones((4, 5, 3), dtype=np.uint8) # HxWxC >>> img = Image.from_numpy(data, color_space=ColorSpace.RGB) >>> assert img.channels == 3 >>> assert img.width == 5 >>> assert img.height == 4
- property layout: ImageLayout#
Return the image layout.
- property pixel_format: PixelFormat#
Return the pixel format.
- print(max_width=256)[source]#
Print the image torch.Tensor to the console.
- Parameters:
max_width (
int, optional) – the widest image, in pixels, that is printed without resizing; seeimage_to_string(). Default:256- Return type:
A
BGRimage is converted to RGB first, so the terminal shows the true colors.img = Image.from_file("panda.png") img.print()
- to(device=None, dtype=None)[source]#
Return the image on
deviceand withdtype, liketorch.Tensor.to().The image itself is not changed; assign the result (
img = img.to(...)). The pixel format’sbit_depthfollows the new dtype.- Parameters:
- Returns:
the image on the given device and with the given dtype.
- Return type:
- Raises:
ValueCheckError – if the image was built with checks disabled and its color space does not fit its channels.
- to_dlpack()[source]#
Return a DLPack capsule from the image torch.Tensor, sharing its memory.
The capsule holds the data in the image’s own
channels_order,(C, H, W)or(H, W, C), and carries no color space; read it back withImage.from_dlpack(capsule, img.pixel_format.color_space, img.channels_order).- Return type:
- to_numpy()[source]#
Return the image data as a numpy array on the CPU, in the stored layout.
The array shares memory with CPU data whose dtype NumPy supports. Bfloat16 data is copied to float32, preserving its values, because NumPy has no bfloat16 dtype.
- Return type:
- write(file_path)[source]#
Write the image to a file.
The format follows the file extension; see
kornia.io.write_image()for the supported formats. ABGRimage is converted to RGB first, so the file holds the true colors.Example
>>> data = np.ones((4, 5, 3), dtype=np.uint8) # HxWxC >>> img = Image.from_numpy(data) >>> import tempfile, os >>> with tempfile.TemporaryDirectory() as tmp: ... img.write(os.path.join(tmp, "test.jpg"))