Skip to content

๐Ÿ Geometric Computer Vision Library for Spatial AI

fix(image): nearest-pixel drawing, clipped rectangles, dtype-independent polygons, validated Image, nearest xterm colours (#5813)

Dmytro Mishkinf1f056ab4f08
diff --git a/changelog.d/5813.added.md b/changelog.d/5813.added.md
new file mode 100644
index 000000000..2f97fe8e9
--- /dev/null
+++ b/changelog.d/5813.added.md
@@ -0,0 +1,4 @@
+`kornia.image.ColorSpace` is exported, so a `PixelFormat` or a colour space for `Image.from_numpy` no longer needs an
+import from `kornia.image.base`. `draw_point2d` and `draw_line` accept a single-value colour, of shape `(1,)` or 0-d,
+and write it to every channel, as `draw_rectangle` and `draw_convex_polygon` already did; they used to raise for it on
+an image with more than one channel. OpenCV's and Pillow's scalar colours fill only the first channel.
diff --git a/changelog.d/5813.breaking.md b/changelog.d/5813.breaking.md
new file mode 100644
index 000000000..c3c649ae0
--- /dev/null
+++ b/changelog.d/5813.breaking.md
@@ -0,0 +1,39 @@
+`draw_point2d`, `draw_line` and `draw_rectangle` place a fractional coordinate on the pixel whose centre is nearest,
+a coordinate exactly halfway rounding up; they used to truncate toward zero, so 2.7 drew at pixel 2 and now draws at
+pixel 3. `draw_point2d` and `draw_line` check their bounds after rounding, so a coordinate lies inside the image
+from -0.5 up to, but not including, `W - 0.5` (`H - 0.5` for y). From `W - 0.5` up to `W`, both used to draw in the
+last column and now raise `ValueError`. `draw_point2d` also raises `ValueError` for any other point outside the
+image: a coordinate between -1 and -0.5 used to draw in the first column, one of -1 or less at the opposite edge,
+and one of `W` or more raised `IndexError`. `draw_line` accepts -0.5 up to 0, which used to raise.
+
+`draw_rectangle` no longer draws a side that lies outside the image, and it clips a fill to the image. It used to
+clamp the corners, which drew such sides along the border; clamp the corners to `[0, W - 1]` and `[0, H - 1]` for
+the old look. It accepts the two corners in either order, where reversed corners drew nothing. It raises
+`ValueError` instead of `AssertionError` when the image and rectangle batch sizes differ or the last dimension is
+not 4, and `ShapeError`, still a `ValueError`, naming the expected shape for an image that is not `(B, C, H, W)`.
+
+`draw_line` draws, at each step along the longer axis, the pixel nearest to the segment, so a line is the same from
+`p1` to `p2` as from `p2` to `p1`. It used to round the shorter-axis coordinate up from `p1`, which put sloped lines
+up to one pixel off and depended on the direction.
+
+`draw_point2d` raises `ValueError` for an image that is not `(C, H, W)` or `(H, W)`; a batched image used to be
+drawn along the wrong axes or raise a torch indexing error.
+
+`Image.to` and `Image.float` return a new `Image` and leave the original unchanged, like `torch.Tensor.to`; they
+used to change the image in place and return it, so code that ignores the result must now assign it
+(`img = img.float()`). `Image` checks its pixel format: `GRAY` needs one channel and `RGB` and `BGR` need three
+(`UNKNOWN` takes any count), and `bit_depth` must be the storage size, `8 * data.element_size()`, where `bit_depth`
+9 to 15 used to pass on `uint8` data and 12 failed on `uint16`. A mismatch raises `ValueCheckError`, a `ValueError`.
+Without a colour space, `Image.from_numpy` and `Image.from_dlpack` label one channel `GRAY`, three `RGB` and any
+other count `UNKNOWN`; they used to label every image `RGB`.
+
+`image_to_string` and `print_image` show each pixel with the nearest of the 240 fixed xterm colours (codes 16 to
+255, the gray ramp included), so printed colours change; they used to pick the nearest of the six colour-cube levels
+in each channel after truncating a float value to a whole level. `print_image` raises `TypeError` instead of
+`RuntimeError` for an input that is neither a path nor a tensor.
+
+`image_to_tensor` raises `TypeError` for any input that is not a `numpy.ndarray`, where a list raised
+`AttributeError`. `make_grid` raises `ValueError` for a negative `padding`, which used to crop the images.
+
+`draw_point2d` no longer exports with `torch.export`, nor to ONNX from torch 2.9, because its out-of-image check
+reads tensor values. `draw_rectangle` exports with `torch.export` from torch 2.14, which it did not before.
diff --git a/changelog.d/5813.fixed.md b/changelog.d/5813.fixed.md
new file mode 100644
index 000000000..6df39ebc3
--- /dev/null
+++ b/changelog.d/5813.fixed.md
@@ -0,0 +1,13 @@
+`draw_convex_polygon` overwrites NaN and infinite pixels inside the polygon, which used to come out NaN, and fills a
+`uint8` image with a float colour, which used to raise `RuntimeError`; the colour is cast to the image dtype. Its
+edges are computed in at least float32 and without rounding the slope first, so they add no error to `bfloat16` or
+`float16` vertices, which are used as given (`bfloat16` vertices at x = 260 and 280, both exact, used to fill columns
+259 to 281), a pixel centre lying exactly on a sloped edge is filled, and a long, shallow edge whose vertices lie
+outside the image is placed correctly. `tensor_to_image` returns a `bfloat16` tensor as a `float32` array instead of
+raising `TypeError`. `Image.from_numpy` accepts a 2-D gray array, which raised `IndexError`. `Image.to` and
+`Image.float` set `bit_depth` from the new dtype, so `clone()` of a converted image no longer raises `BaseError`.
+`Image.write` and `Image.print` convert a `BGR` image to RGB first, so the file and the terminal show the true colours
+instead of red and blue swapped. `print_image` accepts any `os.PathLike` path, such as a `pathlib.Path`. Docstrings:
+the `Image.from_dlpack` example passes a `(C, H, W)` array, `Image.height` and `Image.width` name rows and columns the
+right way round, `Image.write` no longer says it writes only JPEG, and the `image_to_tensor`, `tensor_to_image` and
+`draw_convex_polygon` argument descriptions are corrected.
diff --git a/docs/generate_examples.py b/docs/generate_examples.py
index 33cd556e9..118686408 100644
--- a/docs/generate_examples.py
+++ b/docs/generate_examples.py
@@ -98,6 +98,9 @@ def draw_bbox_kpts(imgs: torch.Tensor, bboxes: torch.Tensor, keypoints: torch.Te
rectangle[..., 2] = bboxes[..., 0] + bboxes[..., -2] # x2
rectangle[..., 3] = bboxes[..., 1] + bboxes[..., -1] # y2
color = torch.tensor([1, 0, 0]).repeat(imgs.shape[0], imgs.shape[1], 1)
+ # keep every box four-sided: a side outside the image is not drawn by draw_rectangle
+ rectangle[..., 0::2] = rectangle[..., 0::2].clamp(0, imgs.shape[-1] - 1)
+ rectangle[..., 1::2] = rectangle[..., 1::2].clamp(0, imgs.shape[-2] - 1)
imgs_draw = K.image.draw_rectangle(imgs, rectangle, color=color)
rectangle2 = torch.zeros(imgs.shape[0], imgs.shape[1], 4)
@@ -107,6 +110,8 @@ def draw_bbox_kpts(imgs: torch.Tensor, bboxes: torch.Tensor, keypoints: torch.Te
rectangle2[..., n, 2] = keypoints[..., n, 0] + 2
rectangle2[..., n, 3] = keypoints[..., n, 1] + 2
color = torch.tensor([0, 0, 1]).repeat(imgs.shape[0], imgs.shape[1], 1)
+ rectangle2[..., 0::2] = rectangle2[..., 0::2].clamp(0, imgs.shape[-1] - 1)
+ rectangle2[..., 1::2] = rectangle2[..., 1::2].clamp(0, imgs.shape[-2] - 1)
return K.image.draw_rectangle(imgs_draw, rectangle2, color=color, fill=True)
@@ -806,9 +811,11 @@ def main():
if confident:
boxes = torch.stack(confident)[None]
for pad in (0, 1, 2): # three passes give a 3 px outline
- out = K.image.draw_rectangle(
- out, boxes + torch.tensor([-pad, -pad, pad, pad]), color=torch.tensor([0.4, 1.0, 0.2])
- )
+ padded = boxes + torch.tensor([-pad, -pad, pad, pad])
+ # keep the outline four-sided for a face at the border
+ padded[..., 0::2] = padded[..., 0::2].clamp(0, out.shape[-1] - 1)
+ padded[..., 1::2] = padded[..., 1::2].clamp(0, out.shape[-2] - 1)
+ out = K.image.draw_rectangle(out, padded, color=torch.tensor([0.4, 1.0, 0.2]))
write_png(OUTPUT_PATH / "face_detection.png", K.image.tensor_to_image((out[0] * 255.0).byte()))
print(f"Generated image example for FaceDetector. {len(confident)} faces")
diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rst
index b65b1dc32..e38d4b4f8 100644
--- a/docs/source/get-started/precision.rst
+++ b/docs/source/get-started/precision.rst
@@ -122,8 +122,10 @@ precision, so the table says nothing about those backends.
* - ``kornia.image``
- โš ๏ธ Partial
- โš ๏ธ Partial
- - 4 / 4
- - ``draw_convex_polygon`` fill accuracy.
+ - 2 / 2
+ - ``draw_convex_polygon`` runs its edge maths in at least float32, so it adds no half-precision error of its
+ own; the vertices are used as given, already rounded to half precision. The circle and ellipse tests still
+ miss because they compute their vertices and their reference mask in half precision.
* - ``kornia.losses``
- โš ๏ธ Partial
- โš ๏ธ Partial
diff --git a/docs/source/image.container.rst b/docs/source/image.container.rst
index b0186a93b..2d3bc4658 100644
--- a/docs/source/image.container.rst
+++ b/docs/source/image.container.rst
@@ -11,6 +11,10 @@ Image container
:members:
:undoc-members:
+.. autoclass:: ColorSpace
+ :members:
+ :undoc-members:
+
.. autoclass:: ChannelsOrder
:members:
:undoc-members:
diff --git a/docs/source/image.rst b/docs/source/image.rst
index 7dce12cc2..bd1d7412e 100644
--- a/docs/source/image.rst
+++ b/docs/source/image.rst
@@ -13,7 +13,7 @@ between tensors and NumPy arrays, and terminal rendering.
:widths: 30 70
* - :doc:`image.container`
- - :class:`Image`, :class:`ImageSize`, :class:`PixelFormat`, :class:`ChannelsOrder` and :class:`ImageLayout`.
+ - :class:`Image`, :class:`ImageSize`, :class:`PixelFormat`, :class:`ColorSpace`, :class:`ChannelsOrder` and :class:`ImageLayout`.
* - :doc:`image.drawing`
- Draw lines, rectangles, convex polygons and points on image tensors.
* - :doc:`image.conversion`
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
index 184e86f43..c77421314 100644
--- a/kornia/contrib/object_detection.py
+++ b/kornia/contrib/object_detection.py
@@ -195,10 +195,11 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
for image, detection in zip(images, dets):
out_img = image[None].clone()
for out in detection:
- out_img = draw_rectangle(
- out_img,
- torch.Tensor([[[out[-4], out[-3], out[-4] + out[-2], out[-3] + out[-1]]]]),
- )
+ box = torch.Tensor([[[out[-4], out[-3], out[-4] + out[-2], out[-3] + out[-1]]]])
+ # a detection that reaches or crosses the border stays visible on all four sides
+ box[..., 0::2] = box[..., 0::2].clamp(0, out_img.shape[-1] - 1)
+ box[..., 1::2] = box[..., 1::2].clamp(0, out_img.shape[-2] - 1)
+ out_img = draw_rectangle(out_img, box)
output.append(out_img[0])
return self._tensor_to_type(output, output_type, is_batch=isinstance(images, torch.Tensor))
diff --git a/kornia/image/__init__.py b/kornia/image/__init__.py
index 002ba3b54..b3c414507 100644
--- a/kornia/image/__init__.py
+++ b/kornia/image/__init__.py
@@ -21,7 +21,7 @@ This package provides image data structures and utilities, including image layou
and channel order definitions.
"""
-from .base import ChannelsOrder, ImageLayout, ImageSize, PixelFormat
+from .base import ChannelsOrder, ColorSpace, ImageLayout, ImageSize, PixelFormat
from .draw import draw_convex_polygon, draw_line, draw_point2d, draw_rectangle
from .image import Image
from .image_print import image_to_string, print_image
@@ -37,6 +37,7 @@ from .utils import (
__all__ = [
"ChannelsOrder",
+ "ColorSpace",
"Image",
"ImageLayout",
"ImageSize",
diff --git a/kornia/image/draw.py b/kornia/image/draw.py
index 4bc0fb0c1..07f45388c 100644
--- a/kornia/image/draw.py
+++ b/kornia/image/draw.py
@@ -26,6 +26,47 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
# TODO: implement width of the line
+def _round_to_pixel(coords: Tensor) -> Tensor:
+ """Return the int64 pixel whose centre is nearest to each coordinate; a coordinate exactly halfway rounds up.
+
+ Pixel ``i`` covers ``[i - 0.5, i + 0.5)``, so ``-0.5`` lands on pixel 0 and ``2.5`` on pixel 3.
+ """
+ if coords.is_floating_point():
+ # x + 0.5 is not representable in float16 / bfloat16 for larger integers (bfloat16 129 + 0.5 -> 130)
+ coords = coords.to(torch.promote_types(coords.dtype, torch.float32))
+ coords = torch.floor(coords + 0.5)
+ return coords.to(torch.int64)
+
+
+def _rectangle_bands(
+ x1: Tensor, y1: Tensor, x2: Tensor, y2: Tensor, h: int, w: int, line_width: int, fill: bool
+) -> Tensor:
+ """Return the row and column slices ``[r0, r1, c0, c1]`` of each rectangle's bands, clipped to a ``h x w`` image.
+
+ The corners are inclusive and ordered (``x1 <= x2``, ``y1 <= y2``) and share any leading shape. The outline is four
+ bands ``line_width`` pixels thick, inside the box; a fill is one band. Each band is drawn as
+ ``image[..., r0:r1, c0:c1]``. Its bounds are clamped to the image, so the part of a band outside the image is an
+ empty slice: a one-pixel side outside the image disappears instead of being moved onto the border. Clamping instead
+ of testing the bounds in Python keeps every corner a tensor until the one ``tolist`` in ``draw_rectangle``, so the
+ function exports to ONNX.
+
+ Returns:
+ an int64 tensor of shape ``(*, K, 4)``: ``K`` is 1 for a fill and 4 for an outline.
+ """
+ if fill:
+ bands = [(y1, y2, x1, x2)]
+ else:
+ bands = [
+ (y1, torch.minimum(y1 + line_width - 1, y2), x1, x2), # top
+ (torch.maximum(y2 - line_width + 1, y1), y2, x1, x2), # bottom
+ (y1, y2, x1, torch.minimum(x1 + line_width - 1, x2)), # left
+ (y1, y2, torch.maximum(x2 - line_width + 1, x1), x2), # right
+ ]
+ r0, r1, c0, c1 = (torch.stack(bound, -1) for bound in zip(*bands))
+ # a start clamped to [0, size] and a stop to [0, size] give an empty slice whenever the band misses the image
+ return torch.stack([r0.clamp(0, h), r1.clamp(-1, h - 1) + 1, c0.clamp(0, w), c1.clamp(-1, w - 1) + 1], -1)
+
+
def draw_point2d(image: Tensor, points: Tensor, color: Tensor) -> Tensor:
r"""Set one or more coordinates in a Tensor to a color.
@@ -34,21 +75,32 @@ def draw_point2d(image: Tensor, points: Tensor, color: Tensor) -> Tensor:
points: the [x, y] points to be drawn on the image with shape :math`(N, 2)`, a single
point with shape :math`(2,)`, or an empty tensor with shape :math`(0, 2)`.
color: the color of the pixel with :math`(C)` where :math`C` is the number of channels of the image.
- A 0-d scalar is accepted when the image has a single channel or is :math`(H,W)`.
+ A single value, with shape :math`(1)` or 0-d, is written to every channel.
Return:
The image with points set to the color. This operation modifies image inplace but also
returns the drawn tensor for convenience. An empty point set leaves the image unchanged.
+ Raises:
+ ValueError: if the image is not ``(C, H, W)`` or ``(H, W)``, or a point lies outside the image after rounding.
+ BaseError: if ``color`` has neither 1 nor ``C`` values, or ``points`` is not ``(2,)`` or ``(N, 2)``.
+
+ Fractional coordinates go to the pixel whose centre is nearest; a coordinate exactly halfway rounds up.
+ A point outside the image raises `ValueError`.
+
"""
+ if image.dim() not in (2, 3):
+ raise ValueError("image must have shape (C, H, W) or (H, W).")
# A 0-d scalar has no channel dimension for the check below to read; treat it as one channel, as draw_line does.
if color.ndim == 0:
color = color.unsqueeze(0)
+ # A single value is written to every channel (see the docstring).
KORNIA_CHECK(
- (len(image.shape) == 2 and len(color.shape) == 1) or (image.shape[0] == color.shape[0]),
+ (len(image.shape) == 2 and len(color.shape) == 1) or color.shape[0] in (1, image.shape[0]),
"Color dim must match the channel dims of the provided image",
)
- points = points.to(dtype=torch.int64, device=image.device)
+ # round on the points' own device: MPS has no float64, and float64 points from NumPy are common
+ points = _round_to_pixel(points).to(image.device)
# A single [x, y] vector is a common call shape; zip(*points) iterated 0-d
# scalars and raised TypeError. An empty (0, 2) set used to fail unpacking;
# indexing with empty columns now leaves the image unchanged.
@@ -58,13 +110,19 @@ def draw_point2d(image: Tensor, points: Tensor, color: Tensor) -> Tensor:
KORNIA_CHECK(points.ndim == 2 and points.shape[-1] == 2, "points must have shape (N, 2)")
x = points[:, 0]
y = points[:, 1]
+ height, width = image.shape[-2:]
+ if ((x < 0) | (x >= width) | (y < 0) | (y >= height)).any():
+ raise ValueError(
+ f"points must lie inside the {height}x{width} image after rounding to the nearest pixel centre: "
+ f"x in [0, {width - 1}], y in [0, {height - 1}]."
+ )
if len(color.shape) == 1:
color = torch.unsqueeze(color, dim=1)
color = color.to(dtype=image.dtype, device=image.device)
if len(image.shape) == 2:
image[y, x] = color
else:
- image[:, y, x] = color
+ image[:, y, x] = color.expand(image.shape[0], -1)
return image
@@ -88,20 +146,28 @@ def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: to
r"""Draw a single line into an image.
Each line is rasterized one pixel per step along its major axis, the one with the larger extent:
- at step ``t = 0 .. major`` the minor coordinate advances by ``ceil(t * minor / major)``, computed in
- integers. Both ``p1`` and ``p2`` are therefore always drawn.
+ at step ``t = 0 .. major`` the pixel is the one whose centre is nearest to the ideal segment, a tie
+ rounding up in absolute coordinates, computed in integers. The line is therefore the same for ``p1 -> p2`` and
+ ``p2 -> p1``, and both ``p1`` and ``p2`` are always drawn. Fractional endpoints go to the pixel whose centre is
+ nearest; a coordinate exactly halfway rounds up.
Args:
image: the input image to where to draw the lines with shape :math`(C,H,W)`.
p1: the start point [x y] of the line with shape (2, ) or (B, 2).
p2: the end point [x y] of the line, with the same shape as ``p1``.
color: the color of the line with shape :math`(C)` where :math`C` is the number of channels
- of the image. A 0-d scalar is accepted when the image has a single channel.
+ of the image. A single value, with shape :math`(1)` or 0-d, is written to every channel.
+ Porting note: OpenCV's and Pillow's scalar colours fill only the first channel.
Return:
The image containing the line. This operation modifies image inplace but also returns
the drawn tensor for convenience.
+ Raises:
+ ValueError: if ``p1`` and ``p2`` differ in shape, or their last dimension is not 2.
+ ValueError: if an endpoint lies outside the image after rounding, or the image is not ``(C, H, W)``.
+ ValueError: if ``color`` has neither 1 nor ``C`` values.
+
Examples:
>>> image = torch.zeros(1, 8, 8)
>>> draw_line(image, torch.tensor([6, 4]), torch.tensor([1, 4]), torch.tensor([255]))
@@ -120,20 +186,12 @@ def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: to
raise ValueError(
"Input points must be 2D points with shape (2, ) or (B, 2) and must have the same batch sizes."
)
- if (
- (p1[..., 0] < 0).any()
- or (p1[..., 0] >= image.shape[-1]).any()
- or (p1[..., 1] < 0).any()
- or (p1[..., 1] >= image.shape[-2]).any()
- ):
- raise ValueError("p1 is out of bounds.")
- if (
- (p2[..., 0] < 0).any()
- or (p2[..., 0] >= image.shape[-1]).any()
- or (p2[..., 1] < 0).any()
- or (p2[..., 1] >= image.shape[-2]).any()
- ):
- raise ValueError("p2 is out of bounds.")
+ # round on the points' own device: MPS has no float64, and float64 points from NumPy are common
+ p1 = _round_to_pixel(p1).to(image.device)
+ p2 = _round_to_pixel(p2).to(image.device)
+ for name, p in (("p1", p1), ("p2", p2)):
+ if ((p[..., 0] < 0) | (p[..., 0] >= image.shape[-1]) | (p[..., 1] < 0) | (p[..., 1] >= image.shape[-2])).any():
+ raise ValueError(f"{name} is out of bounds.")
if len(image.size()) != 3:
raise ValueError("image must have 3 dimensions (C,H,W).")
@@ -143,13 +201,10 @@ def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: to
if color.ndim == 0:
color = color.unsqueeze(0)
- if color.size(0) != image.size(0):
+ if color.size(0) not in (1, image.size(0)):
raise ValueError("color must have the same number of channels as the image.")
- # move p1 and p2 to the same device as the input image
# move color to the same device and dtype as the input image
- p1 = p1.to(image.device).to(torch.int64)
- p2 = p2.to(image.device).to(torch.int64)
color = color.to(image)
p1 = p1.reshape(-1, 2)
@@ -161,12 +216,12 @@ def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: to
dy_sign = torch.sign(dy)
dx, dy = torch.abs(dx), torch.abs(dy)
- # Every line steps one pixel at a time along its major axis and places the minor coordinate at
- # ceil(t * minor / major). The (line, t) pairs with t <= major are taken first, so the work is one
- # entry per drawn pixel rather than a (B, longest line) grid that pads every short line out. The
- # ceiling is taken in integers: a float step lands just above an exact integer quotient and rounds
- # it up a pixel. A vertical or horizontal line has minor = 0, and a single point has major = 0,
- # which the clamp keeps from dividing by 0. An empty batch draws nothing.
+ # Every line steps one pixel at a time along its major axis and places the minor coordinate at the pixel
+ # nearest to m1 + s * t * minor / major, halfway rounding up in absolute coordinates (so p1 <-> p2 gives the
+ # same pixels). The (line, t) pairs with t <= major are taken first, so the work is one entry per drawn
+ # pixel rather than a (B, longest line) grid that pads every short line out. The rounding is taken in
+ # integers: a float step lands just off an exact tie. A vertical or horizontal line has minor = 0, and a
+ # single point has major = 0, which the clamp keeps from dividing by 0. An empty batch draws nothing.
x_major = dx > dy
major = torch.where(x_major, dx, dy)
minor = torch.where(x_major, dy, dx)
@@ -174,14 +229,19 @@ def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: to
steps = torch.arange(num_steps, device=image.device).unsqueeze(0)
line, t = (steps <= major).nonzero(as_tuple=True)
divisor = major[line, 0].clamp_min(1)
- t_minor = torch.div(t * minor[line, 0] + divisor - 1, divisor, rounding_mode="floor")
x_maj = x_major[line, 0]
- x_coords = x1[line, 0] + dx_sign[line, 0] * torch.where(x_maj, t, t_minor)
- y_coords = y1[line, 0] + dy_sign[line, 0] * torch.where(x_maj, t_minor, t)
+ m1 = torch.where(x_maj, y1[line, 0], x1[line, 0])
+ s_minor = torch.where(x_maj, dy_sign[line, 0], dx_sign[line, 0])
+ # floor((2 * m1 * major + 2 * s * t * minor + major) / (2 * major)) = round-half-up(m1 + s * t * minor / major)
+ m_coords = torch.div(
+ 2 * m1 * divisor + 2 * s_minor * t * minor[line, 0] + divisor, 2 * divisor, rounding_mode="floor"
+ )
+ x_coords = torch.where(x_maj, x1[line, 0] + dx_sign[line, 0] * t, m_coords)
+ y_coords = torch.where(x_maj, m_coords, y1[line, 0] + dy_sign[line, 0] * t)
x_coords = torch.clamp(x_coords, min=0, max=image.shape[-1] - 1)
y_coords = torch.clamp(y_coords, min=0, max=image.shape[-2] - 1)
- image[:, y_coords, x_coords] = color.view(-1, 1)
+ image[:, y_coords, x_coords] = color.view(-1, 1).expand(image.size(0), -1)
return image
@@ -199,6 +259,14 @@ def draw_rectangle(
If C is 3, and color is 1 channel it will be broadcasted.
fill: is a flag used to fill the boxes with color if True.
+ Corners may come in either order. Coordinates are rounded to the nearest pixel centre (a coordinate exactly
+ halfway rounds up), and the rectangle includes both corners. A side outside the image is not drawn and a fill is
+ clipped to the image.
+
+ Raises:
+ ShapeError: if the image is not ``(B, C, H, W)``. It is also a ``ValueError``.
+ ValueError: if ``rectangle`` is not ``(B, N, 4)``, or its batch size differs from the image's.
+
Returns:
This operation modifies image inplace but also returns the drawn tensor for
convenience with same shape the of the input BxCxHxW.
@@ -209,19 +277,19 @@ def draw_rectangle(
>>> out = draw_rectangle(img, rect)
"""
+ KORNIA_CHECK_SHAPE(image, ["B", "C", "H", "W"])
batch, c, h, w = image.shape
batch_rect, num_rectangle, num_points = rectangle.shape
if batch != batch_rect:
- raise AssertionError("Image batch and rectangle batch must be equal")
+ raise ValueError("Image batch and rectangle batch must be equal")
if num_points != 4:
- raise AssertionError("Number of points in rectangle must be 4")
-
- # clone rectangle, in case it's been expanded assignment from clipping causes problems
- rectangle = rectangle.long().clone()
+ raise ValueError("Number of points in rectangle must be 4")
- # clip rectangle to hxw bounds
- rectangle[:, :, 1::2] = torch.clamp(rectangle[:, :, 1::2], 0, h - 1)
- rectangle[:, :, ::2] = torch.clamp(rectangle[:, :, ::2], 0, w - 1)
+ rect = _round_to_pixel(rectangle)
+ x1 = torch.minimum(rect[..., 0], rect[..., 2])
+ x2 = torch.maximum(rect[..., 0], rect[..., 2])
+ y1 = torch.minimum(rect[..., 1], rect[..., 3])
+ y2 = torch.maximum(rect[..., 1], rect[..., 3])
if color is None:
color = torch.tensor([0.0] * c).expand(batch, num_rectangle, c)
@@ -236,28 +304,12 @@ def draw_rectangle(
if color_channels == 1 and c == 3:
color = color.expand(batch, num_rectangle, c)
+ # one host read for the bands of every rectangle
+ bands = _rectangle_bands(x1, y1, x2, y2, h, w, 1, fill).tolist()
for b in range(batch):
for n in range(num_rectangle):
- if fill:
- image[
- b,
- :,
- int(rectangle[b, n, 1]) : int(rectangle[b, n, 3] + 1),
- int(rectangle[b, n, 0]) : int(rectangle[b, n, 2] + 1),
- ] = color[b, n, :, None, None]
- else:
- image[b, :, int(rectangle[b, n, 1]) : int(rectangle[b, n, 3] + 1), rectangle[b, n, 0]] = color[
- b, n, :, None
- ]
- image[b, :, int(rectangle[b, n, 1]) : int(rectangle[b, n, 3] + 1), rectangle[b, n, 2]] = color[
- b, n, :, None
- ]
- image[b, :, rectangle[b, n, 1], int(rectangle[b, n, 0]) : int(rectangle[b, n, 2] + 1)] = color[
- b, n, :, None
- ]
- image[b, :, rectangle[b, n, 3], int(rectangle[b, n, 0]) : int(rectangle[b, n, 2] + 1)] = color[
- b, n, :, None
- ]
+ for r0, r1, c0, c1 in bands[b][n]:
+ image[b, :, r0:r1, c0:c1] = color[b, n, :, None, None]
return image
@@ -276,7 +328,9 @@ def _get_convex_edges(polygon: Tensor, h: int, w: int) -> Tuple[Tensor, Tensor]:
The left and right edges of the polygon of shape (B,B).
"""
- dtype = polygon.dtype
+ # The edge maths runs in at least float32: half-precision vertices cannot resolve the scanline grid.
+ dtype = torch.promote_types(polygon.dtype, torch.float32)
+ polygon = polygon.to(dtype)
# A single vertex is its own first and last point, so the loop below would leave no edge;
# draw it as a zero-length edge, like a two-vertex polygon whose vertices coincide.
@@ -297,8 +351,14 @@ def _get_convex_edges(polygon: Tensor, h: int, w: int) -> Tuple[Tensor, Tensor]:
# so its dx is set to 0. An epsilon added to dy instead underflows in float16 (0 / 0 blanks the scanline), and
# in float64 it shifts a sloped edge enough to drop a pixel centre lying exactly on it.
dy = y_end - y_start
- dx = torch.where(dy == 0, 0.0, (x_end - x_start) / dy).clamp(-w, w)
- xs = (ys[..., :, None] - y_start[..., None, :]) * dx[..., None, :] + x_start[..., None, :]
+ dx = x_end - x_start
+ # Multiply before dividing: dx / dy first rounds the slope, which drops a centre lying exactly on the edge.
+ safe_dy = torch.where(dy == 0, torch.ones_like(dy), dy)
+ xs = torch.where(
+ dy[..., None, :] == 0,
+ x_start[..., None, :],
+ (ys[..., :, None] - y_start[..., None, :]) * dx[..., None, :] / safe_dy[..., None, :] + x_start[..., None, :],
+ )
# Only count edge in their active regions (i.e between the vertices)
valid_edges = (y_start[..., None, :] <= ys[..., :, None]).logical_and(ys[..., :, None] <= y_end[..., None, :])
@@ -347,12 +407,18 @@ def draw_convex_polygon(images: Tensor, polygons: Union[Tensor, List[Tensor]], c
polygons: represents polygons as points, either BxNx2 or List of variable length polygons.
N is the number of points.
2 is (x, y).
- colors: a B x 3 tensor, 3 tensor, or 0-d scalar with color to fill in.
+ colors: a ``B x C`` tensor, a ``C`` tensor, or a 0-d scalar with the fill colour.
Returns:
This operation modifies image inplace but also returns the drawn tensor for
convenience with same shape the of the input BxCxHxW.
+ Raises:
+ ShapeError: if the images are not ``(B, C, H, W)``. It is also a ``ValueError``.
+ ValueError: if ``polygons`` is a tensor that is not three dimensional.
+ BaseError: if the vertices are not ``(x, y)`` points.
+ BaseError: if the images, polygons and colors differ in batch size or device.
+
Note:
This function assumes a coordinate system (0, h - 1), (0, w - 1) in the image, with (0, 0) being the center
of the top-left pixel and (w - 1, h - 1) being the center of the bottom-right coordinate.
@@ -372,7 +438,7 @@ def draw_convex_polygon(images: Tensor, polygons: Union[Tensor, List[Tensor]], c
empty_polygons = torch.tensor([len(p) == 0 for p in polygons], dtype=torch.bool, device=device)
# `[]` has no polygon to take a dtype or device from; an empty (0, 0, 2) batch returns below.
polygons = _batch_polygons(polygons) if polygons else images.new_zeros(0, 0, 2)
- b_p, _, xy, device_p, dtype_p = *polygons.shape, polygons.device, polygons.dtype
+ b_p, _, xy, device_p = *polygons.shape, polygons.device
if len(colors.shape) <= 1:
colors = colors.expand(b_i, c_i)
b_c, _, device_c = *colors.shape, colors.device
@@ -384,9 +450,10 @@ def draw_convex_polygon(images: Tensor, polygons: Union[Tensor, List[Tensor]], c
return images
x_left, x_right = _get_convex_edges(polygons, h_i, w_i)
- ws = torch.arange(w_i, device=device, dtype=dtype_p)[None, None, :]
+ ws = torch.arange(w_i, device=device, dtype=x_left.dtype)[None, None, :]
fill_region = (ws >= x_left[..., :, None]) & (ws <= x_right[..., :, None])
if empty_polygons is not None:
fill_region &= ~empty_polygons[:, None, None]
- images.mul_(~fill_region[:, None]).add_(fill_region[:, None] * colors[..., None, None])
+ fill = fill_region[:, None]
+ images.copy_(torch.where(fill, colors[..., None, None].to(images.dtype), images))
return images
diff --git a/kornia/image/image.py b/kornia/image/image.py
index 8e96a2916..d01ce5272 100644
--- a/kornia/image/image.py
+++ b/kornia/image/image.py
@@ -18,13 +18,14 @@
from __future__ import annotations
from pathlib import Path
-from typing import Any, Union
+from typing import Any, Optional, Union
import torch
from torch.utils.dlpack import from_dlpack, to_dlpack
import kornia.color
-from kornia.core.check import KORNIA_CHECK
+from kornia.core.check import are_checks_enabled
+from kornia.core.exceptions import ValueCheckError
from kornia.image.base import (
KORNIA_CHECK_IMAGE_LAYOUT,
ChannelsOrder,
@@ -41,6 +42,15 @@ np_ndarray = Any
DLPack = Any
+# the channel count each colour space implies; UNKNOWN accepts any count
+_CHANNELS_OF_COLOR_SPACE = {ColorSpace.GRAY: 1, ColorSpace.RGB: 3, ColorSpace.BGR: 3}
+
+
+def _default_color_space(channels: int) -> ColorSpace:
+ """Label an image by its channel count: 1 is GRAY, 3 is RGB, anything else is UNKNOWN."""
+ return {1: ColorSpace.GRAY, 3: ColorSpace.RGB}.get(channels, ColorSpace.UNKNOWN)
+
+
class Image:
r"""Class that holds an Image torch.Tensor representation.
@@ -56,6 +66,9 @@ class Image:
Args:
data: a torch torch.Tensor containing the image data.
+ pixel_format: the pixel format. ``bit_depth`` is the storage size, ``8 * data.element_size()``, and the color
+ space must match the channel count: ``GRAY`` has 1 channel, ``RGB`` and ``BGR`` have 3, ``UNKNOWN``
+ accepts any count.
layout: a dataclass containing the image layout information.
Examples:
@@ -85,14 +98,37 @@ class Image:
def __init__(self, data: torch.Tensor, pixel_format: PixelFormat, layout: ImageLayout) -> None:
"""Image constructor.
+ Like the other kornia checks, the pixel-format checks are skipped after ``kornia.core.check.disable_checks()``.
+
Args:
data: a torch torch.Tensor containing the image data.
pixel_format: the pixel format of the image.
layout: a dataclass containing the image layout information.
+ Raises:
+ ShapeError: if ``data`` does not have the shape ``layout`` describes. It is also a ``ValueError``.
+ ValueCheckError: if ``pixel_format.bit_depth`` is not ``8 * data.element_size()`` (also a ``ValueError``).
+ ValueCheckError: if the color space does not match the channel count. It is also a ``ValueError``.
+
"""
KORNIA_CHECK_IMAGE_LAYOUT(data, layout)
- KORNIA_CHECK(data.element_size() == pixel_format.bit_depth // 8, "Invalid bit depth.")
+ if are_checks_enabled():
+ storage_bits = 8 * data.element_size()
+ if pixel_format.bit_depth != storage_bits:
+ raise ValueCheckError(
+ f"Invalid bit depth: the pixel format says {pixel_format.bit_depth} bits but the data is stored "
+ f"in {storage_bits} bits ({data.dtype}).",
+ actual_value=pixel_format.bit_depth,
+ expected_range=(storage_bits, storage_bits),
+ )
+ expected_channels = _CHANNELS_OF_COLOR_SPACE.get(pixel_format.color_space)
+ if expected_channels is not None and layout.channels != expected_channels:
+ raise ValueCheckError(
+ f"Invalid color space: {pixel_format.color_space.name} needs {expected_channels} channel(s) but "
+ f"the layout has {layout.channels}. Use ColorSpace.UNKNOWN for other channel counts.",
+ actual_value=layout.channels,
+ expected_range=(expected_channels, expected_channels),
+ )
self._data = data
self._pixel_format = pixel_format
@@ -103,21 +139,27 @@ class Image:
# TODO: explore use TensorWrapper
def to(self, device: Union[str, torch.device, None] = None, dtype: Union[torch.dtype, None] = None) -> Image:
- """Move the image to the given device and dtype.
+ """Return the image on ``device`` and with ``dtype``, like :meth:`torch.Tensor.to`.
+
+ The image itself is not changed; assign the result (``img = img.to(...)``). The pixel format's ``bit_depth``
+ follows the new dtype.
Args:
device: the device to move the image to.
dtype: the data type to cast the image to.
Returns:
- Image: the image moved to the given device and dtype.
+ Image: the image on the given device and with the given dtype.
+
+ Raises:
+ ValueCheckError: if the image was built with checks disabled and its color space does not fit its channels.
"""
if device is not None and isinstance(device, torch.dtype):
dtype, device = device, None
- # put the data to the device and dtype
- self._data = self.data.to(device, dtype)
- return self
+ data = self.data.to(device, dtype)
+ pixel_format = PixelFormat(color_space=self.pixel_format.color_space, bit_depth=data.element_size() * 8)
+ return Image(data, pixel_format, self.layout)
# TODO: explore use TensorWrapper
def clone(self) -> Image:
@@ -166,12 +208,12 @@ class Image:
@property
def height(self) -> int:
- """Return the image height (columns)."""
+ """Return the image height (number of rows)."""
return int(self.layout.image_size.height)
@property
def width(self) -> int:
- """Return the image width (rows)."""
+ """Return the image width (number of columns)."""
return int(self.layout.image_size.width)
@property
@@ -181,9 +223,8 @@ class Image:
# TODO: figure out a better way map this function
def float(self) -> Image:
- """Return the image as float."""
- self._data = self.data.float()
- return self
+ """Return the image as float32; the image itself is not changed."""
+ return self.to(dtype=torch.float32)
def to_gray(self) -> Image:
"""Convert the image to grayscale."""
@@ -274,16 +315,24 @@ class Image:
def from_numpy(
cls,
data: np_ndarray,
- color_space: ColorSpace = ColorSpace.RGB,
+ color_space: Optional[ColorSpace] = None,
channels_order: ChannelsOrder = ChannelsOrder.CHANNELS_LAST,
) -> Image:
"""Construct an image torch.Tensor from a numpy array.
Args:
data: a numpy array containing the image data.
- color_space: the color space of the image.
+ color_space: the color space of the image. If ``None``, a 1-channel array is ``GRAY``, a 3-channel
+ array is ``RGB`` and any other channel count is ``UNKNOWN``. An explicit color space that does not
+ match the channel count raises.
channels_order: what dimension the channels are in the image torch.Tensor.
+ Raises:
+ ValueError: if ``channels_order`` is neither ``CHANNELS_LAST`` nor ``CHANNELS_FIRST``.
+ ValueCheckError: if an explicit ``color_space`` does not match the channel count (also a ``ValueError``).
+ ShapeError: if ``data`` has more than three dimensions. It is also a ``ValueError``.
+ IndexError: if ``data`` has fewer than two dimensions.
+
Example:
>>> data = np.ones((4, 5, 3), dtype=np.uint8) # HxWxC
>>> img = Image.from_numpy(data, color_space=ColorSpace.RGB)
@@ -292,6 +341,9 @@ class Image:
>>> assert img.height == 4
"""
+ if data.ndim == 2:
+ # a single-channel image without a channel axis
+ data = data[..., None] if channels_order == ChannelsOrder.CHANNELS_LAST else data[None]
if channels_order == ChannelsOrder.CHANNELS_LAST:
image_size = ImageSize(height=data.shape[0], width=data.shape[1])
channels = data.shape[2]
@@ -301,6 +353,8 @@ class Image:
else:
raise ValueError("channels_order must be either `CHANNELS_LAST` or `CHANNELS_FIRST`")
+ if color_space is None:
+ color_space = _default_color_space(channels)
# create the pixel format based on the input data
pixel_format = PixelFormat(color_space=color_space, bit_depth=data.itemsize * 8)
@@ -319,16 +373,23 @@ class Image:
"""Construct an image torch.Tensor from a DLPack capsule.
Args:
- data: a DLPack capsule from numpy, tvm or jax.
+ data: a DLPack capsule from numpy, tvm or jax. The capsule must hold a ``(C, H, W)`` image; it is
+ labelled ``GRAY`` for 1 channel, ``RGB`` for 3 and ``UNKNOWN`` otherwise.
+
+ Raises:
+ ShapeError: if the capsule has more than three dimensions. It is also a ``ValueError``.
+ IndexError: if the capsule has fewer than three dimensions.
Example:
- >>> x = np.ones((4, 5, 3))
+ >>> x = np.ones((3, 4, 5)) # (C, H, W)
>>> img = Image.from_dlpack(x.__dlpack__())
+ >>> img.channels, img.height, img.width
+ (3, 4, 5)
"""
_data: torch.Tensor = from_dlpack(data)
- pixel_format = PixelFormat(color_space=ColorSpace.RGB, bit_depth=_data.element_size() * 8)
+ pixel_format = PixelFormat(color_space=_default_color_space(_data.shape[0]), bit_depth=_data.element_size() * 8)
# create the image layout based on the input data
layout = ImageLayout(
@@ -366,7 +427,8 @@ class Image:
def write(self, file_path: str | Path) -> None:
"""Write the image to a file.
- For now, only support writing to JPEG format.
+ The format follows the file extension; see :func:`kornia.io.write_image` for the supported formats. A ``BGR``
+ image is converted to RGB first, so the file holds the true colours.
Args:
file_path: the path to the file to write the image to.
@@ -374,10 +436,12 @@ class Image:
Example:
>>> data = np.ones((4, 5, 3), dtype=np.uint8) # HxWxC
>>> img = Image.from_numpy(data)
- >>> img.write("test.jpg")
+ >>> import tempfile, os
+ >>> with tempfile.TemporaryDirectory() as tmp:
+ ... img.write(os.path.join(tmp, "test.jpg"))
"""
- data = self.data
+ data = self.to_rgb().data if self.pixel_format.color_space == ColorSpace.BGR else self.data
if self.channels_order == ChannelsOrder.CHANNELS_LAST:
data = data.permute(2, 0, 1)
write_image(file_path, data)
@@ -388,6 +452,8 @@ class Image:
Args:
max_width: the maximum width of the image to print.
+ A ``BGR`` image is converted to RGB first, so the terminal shows the true colours.
+
.. code-block:: python
img = Image.from_file("panda.png")
@@ -396,7 +462,7 @@ class Image:
.. image:: https://github.com/kornia/data/blob/main/print_image.png?raw=true
"""
- data = self.data
+ data = self.to_rgb().data if self.pixel_format.color_space == ColorSpace.BGR else self.data
if self.channels_order == ChannelsOrder.CHANNELS_LAST:
data = data.permute(2, 0, 1)
print(image_to_string(data, max_width)) # noqa: T201 - Image.print prints by design
diff --git a/kornia/image/image_print.py b/kornia/image/image_print.py
index 28b299156..85a69c29b 100644
--- a/kornia/image/image_print.py
+++ b/kornia/image/image_print.py
@@ -23,6 +23,7 @@ Nice long listing of all 256 colors and their codes.
Taken from https://gist.github.com/klange/1687427
"""
+import os
import re
from typing import Tuple, Union
@@ -299,6 +300,25 @@ CLUT = [
SHORT2RGB_DICT = dict(CLUT)
RGB2SHORT_DICT = {v: k for k, v in SHORT2RGB_DICT.items()}
+# codes 16-255 (codes 0-15 are defined by the terminal, not fixed): (240, 3) RGB values
+_XTERM_CODES = torch.arange(16, 256)
+_XTERM_RGB = torch.tensor(
+ [[int(SHORT2RGB_DICT[str(c)][i : i + 2], 16) for i in (0, 2, 4)] for c in range(16, 256)], dtype=torch.float64
+)
+_XTERM_RGB_SQ = (_XTERM_RGB**2).sum(1)
+# pixels per distance computation: the (chunk, 240) float64 matrix stays near 31 MB whatever the image size
+_PIXELS_PER_CHUNK = 16384
+
+
+def _nearest_xterm_codes(rgb: torch.Tensor) -> torch.Tensor:
+ """Return the code (16-255) of the fixed xterm colour nearest to each row of an (N, 3) float64 RGB tensor.
+
+ The distance is the squared RGB distance; ``argmin`` takes the lowest code on a tie.
+ """
+ dist = rgb @ _XTERM_RGB.T
+ dist.mul_(-2).add_(_XTERM_RGB_SQ).add_((rgb**2).sum(1, keepdim=True))
+ return _XTERM_CODES[dist.argmin(1)]
+
def _str2hex(hexstr: str) -> int:
return int(hexstr, 16)
@@ -355,7 +375,9 @@ def rgb2short(rgb: str) -> Tuple[str, str]:
def image_to_string(image: torch.Tensor, max_width: int = 256) -> str:
"""Obtain the closest xterm-256 approximation string from an image torch.Tensor.
- The torch.Tensor shall be either 0~1 float type or 0~255 long type.
+ The torch.Tensor shall be either 0~1 float type or 0~255 long type. Each pixel is shown with the nearest of the
+ 240 fixed xterm-256 colours (codes 16-255, the 6x6x6 cube and the gray ramp) by RGB distance, measured from its
+ unrounded 0-255 value; codes 0-15 are defined by the terminal and are not used.
Args:
image: an RGB image with shape :math:`3HW` or a grayscale image with shape :math:`1HW`.
@@ -371,25 +393,25 @@ def image_to_string(image: torch.Tensor, max_width: int = 256) -> str:
new_h = max(1, image.size(-2) * max_width // image.size(-1))
image = kornia.geometry.resize(image, (new_h, max_width))
- image = (image * 255).clamp(0, 255).long()
+ # the 0-255 value, unrounded: a float pixel is matched at its own value (an integer input stays exact)
+ image = (image * 255).clamp(0, 255)
if image.shape[0] == 1:
# a grey value is the same colour in each of the three terminal components
image = image.expand(3, -1, -1)
H, W = image.shape[-2:]
- flat = image.permute(1, 2, 0).reshape(-1, 3)
+ # to the CPU first, then float64: MPS has no float64, and one combined .to() returns zeros there on recent torch
+ flat = image.permute(1, 2, 0).reshape(-1, 3).cpu().to(torch.float64)
+ # nearest fixed colour per pixel, a chunk of pixels at a time so the distance matrix stays small
+ codes = torch.cat([_nearest_xterm_codes(chunk) for chunk in flat.split(_PIXELS_PER_CHUNK)]).tolist()
- rgb2short_fn = rgb2short
lines = []
idx = 0
for _ in range(H):
row_parts = []
for _ in range(W):
- r, g, b = flat[idx].tolist()
- h = f"{r:02x}{g:02x}{b:02x}"
- short, _ = rgb2short_fn(h)
- row_parts.append(f"\033[48;5;{short}m ")
+ row_parts.append(f"\033[48;5;{codes[idx]}m ")
idx += 1
row_parts.append("\033[0m\n")
lines.append("".join(row_parts))
@@ -397,25 +419,33 @@ def image_to_string(image: torch.Tensor, max_width: int = 256) -> str:
return "".join(lines)
-def print_image(image: Union[str, torch.Tensor], max_width: int = 96) -> None:
+def print_image(image: Union[str, os.PathLike, torch.Tensor], max_width: int = 96) -> None:
"""Print an image to the terminal.
.. image:: https://github.com/kornia/data/blob/main/print_image.png?raw=true
Args:
- image: path to a valid image file or a torch.Tensor.
+ image: path (``str`` or ``os.PathLike``) to a valid image file, or a torch.Tensor.
max_width: maximum width to print to terminal.
+ Raises:
+ TypeError: if ``image`` is neither a path nor a tensor.
+ ShapeError: if the tensor is not ``(C, H, W)``. It is also a ``ValueError``.
+ ImageError: if the tensor has neither 1 nor 3 channels. It is also a ``ValueError``.
+ ValueCheckError: if a float tensor has values outside [0, 1], or an integer one outside [0, 255].
+ FileNotFoundError: if the path does not exist. Other errors of :func:`kornia.io.load_image` pass through.
+
Note:
Need to use `print_image(...)`.
"""
- if isinstance(image, str):
+ if isinstance(image, (str, os.PathLike)):
from kornia.io import ImageLoadType # pylint: disable=C0415
- img = kornia.io.load_image(image, ImageLoadType.RGB8)
+ # os.fsdecode: a path-like object may return bytes from __fspath__, which load_image's Path() rejects
+ img = kornia.io.load_image(os.fsdecode(image), ImageLoadType.RGB8)
elif isinstance(image, torch.Tensor):
img = image
else:
- raise RuntimeError(f"Expect image type to be either torch.Tensor or str. Got {type(image)}.")
+ raise TypeError(f"Expect image type to be either torch.Tensor, str or os.PathLike. Got {type(image)}.")
print(image_to_string(img, max_width)) # noqa: T201 - print_image prints by design
diff --git a/kornia/image/utils.py b/kornia/image/utils.py
index f16d4cd96..1b6118fbd 100644
--- a/kornia/image/utils.py
+++ b/kornia/image/utils.py
@@ -19,23 +19,28 @@
from functools import wraps
from typing import Any, Callable, List, Optional
+import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
def image_to_tensor(image: Any, keepdim: bool = True) -> torch.Tensor:
- """Convert a numpy image to a PyTorch 4d tensor image.
+ """Convert a NumPy image to a PyTorch tensor image.
Args:
image: image of the form :math:`(H, W, C)`, :math:`(H, W)` or
:math:`(B, H, W, C)`.
- keepdim: If ``False`` unsqueeze the input image to match the shape
- :math:`(B, H, W, C)`.
+ keepdim: If ``False``, a 2-D or 3-D input gets a leading batch axis, :math:`(1, C, H, W)`. A 4-D input is
+ always :math:`(B, C, H, W)`.
Returns:
- tensor of the form :math:`(B, C, H, W)` if keepdim is ``False``,
- :math:`(C, H, W)` otherwise.
+ tensor of the form :math:`(C, H, W)` for a 2-D or 3-D input with ``keepdim=True`` (a 2-D input has
+ :math:`C = 1`), and :math:`(B, C, H, W)` otherwise.
+
+ Raises:
+ TypeError: if ``image`` is not a ``numpy.ndarray``.
+ ValueError: if ``image`` is not two, three or four dimensional.
Example:
>>> img = np.ones((3, 3))
@@ -51,6 +56,9 @@ def image_to_tensor(image: Any, keepdim: bool = True) -> torch.Tensor:
torch.Size([1, 3, 4, 4])
"""
+ if not isinstance(image, np.ndarray):
+ raise TypeError(f"Input type is not a numpy.ndarray. Got {type(image)}")
+
if len(image.shape) > 4 or len(image.shape) < 2:
raise ValueError("Input size must be a two, three or four dimensional array")
@@ -174,10 +182,15 @@ def tensor_to_image(tensor: torch.Tensor, keepdim: bool = False, force_contiguou
:math:`(B, C, H, W)`.
keepdim: If ``False`` squeeze the input image to match the shape
:math:`(H, W, C)` or :math:`(H, W)`.
- force_contiguous: If ``True`` call `contiguous` to the tensor before
+ force_contiguous: If ``True``, call ``contiguous`` on the result before converting it to NumPy.
Returns:
- image of the form :math:`(H, W)`, :math:`(H, W, C)` or :math:`(B, H, W, C)`.
+ image of the form :math:`(H, W)`, :math:`(H, W, C)` or :math:`(B, H, W, C)`. A ``bfloat16`` tensor is
+ returned as ``float32``.
+
+ Raises:
+ TypeError: if ``tensor`` is not a ``torch.Tensor``.
+ ValueError: if ``tensor`` is not two, three or four dimensional.
Example:
>>> img = torch.ones(1, 3, 3)
@@ -197,6 +210,8 @@ def tensor_to_image(tensor: torch.Tensor, keepdim: bool = False, force_contiguou
input_shape = tensor.shape
image = tensor.cpu().detach()
+ if image.dtype == torch.bfloat16:
+ image = image.float() # NumPy has no bfloat16
if len(input_shape) == 2:
# (H, W) -> (H, W)
@@ -224,10 +239,11 @@ def tensor_to_image(tensor: torch.Tensor, keepdim: bool = False, force_contiguou
class ImageToTensor(nn.Module):
- """Converts a numpy image to a PyTorch 4d tensor image.
+ """Convert a NumPy image to a PyTorch tensor image with :func:`image_to_tensor`.
Args:
- keepdim: If ``False`` unsqueeze the input image to match the shape :math:`(B, H, W, C)`.
+ keepdim: If ``False``, a 2-D or 3-D input gets a leading batch axis, :math:`(1, C, H, W)`. A 4-D input is
+ always :math:`(B, C, H, W)`.
"""
@@ -259,14 +275,20 @@ def make_grid(tensor: torch.Tensor, n_row: Optional[int] = None, padding: int =
tensor: A batched tensor of shape (B, C, H, W).
n_row: Number of images displayed in each row of the grid. If ``None``, use the square root
of the batch size rounded up. Images are placed in batch order, filling each row before the next.
- padding: The amount of padding to add between images.
+ padding: The amount of padding to add between images; must be non-negative.
Returns:
torch.Tensor: The combined image grid.
+ Raises:
+ TypeError: if ``tensor`` is not a ``torch.Tensor``.
+ ValueError: if ``tensor`` is not four dimensional, ``n_row`` is not positive or ``padding`` is negative.
+
"""
if not isinstance(tensor, torch.Tensor):
raise TypeError("Input tensor must be a PyTorch tensor.")
+ if padding < 0:
+ raise ValueError("padding must be non-negative.")
B, C, H, W = tensor.shape
if n_row is None:
diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.py
index 2ae9545f8..48b992368 100644
--- a/testing/half_precision_eager_rng.py
+++ b/testing/half_precision_eager_rng.py
@@ -199,7 +199,7 @@ AUDITED_EAGER_RNG_CALLS = tuple(
),
*_audited(
"tests/image/test_draw.py",
- 366,
+ 423,
"torch.rand",
4,
("tests/image/test_draw.py::TestDrawLine::test_point_size",),
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index f61cbd6f3..21d21e723 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -404,8 +404,6 @@ call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestGet
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestPerspectiveTransform3D::test_get_perspective_transform3d_2[cpu-bfloat16-1]
call builtins.AssertionError tests/image/test_draw.py::TestFillConvexPolygon::test_circle[cpu-bfloat16]
call builtins.AssertionError tests/image/test_draw.py::TestFillConvexPolygon::test_ellipse[cpu-bfloat16]
-call builtins.AssertionError tests/image/test_draw.py::TestFillConvexPolygon::test_out_of_bounds_rectangle[cpu-bfloat16]
-call builtins.TypeError tests/image/test_image_utils.py::test_tensor_to_image_contiguous[cpu-bfloat16]
call builtins.AssertionError tests/integration/test_conversions.py::TestAngleOfRotations::test_axis_angle[cpu-bfloat16--45.0-x]
call builtins.AssertionError tests/integration/test_conversions.py::TestAngleOfRotations::test_axis_angle[cpu-bfloat16--45.0-y]
call builtins.AssertionError tests/integration/test_conversions.py::TestAngleOfRotations::test_axis_angle[cpu-bfloat16--45.0-z]
diff --git a/tests/api_surface.json b/tests/api_surface.json
index 6c60453f6..ee16cc4ac 100644
--- a/tests/api_surface.json
+++ b/tests/api_surface.json
@@ -604,6 +604,7 @@
],
"kornia.image": [
"ChannelsOrder",
+ "ColorSpace",
"Image",
"ImageLayout",
"ImageSize",
diff --git a/tests/image/test_draw.py b/tests/image/test_draw.py
index b4c4e427d..ba1a52762 100644
--- a/tests/image/test_draw.py
+++ b/tests/image/test_draw.py
@@ -15,17 +15,20 @@
# limitations under the License.
#
+import io
import math
+import warnings
import pytest
import torch
-from kornia.core.exceptions import BaseError
+from kornia.core._compat import torch_version_ge
+from kornia.core.exceptions import BaseError, ShapeError
from kornia.geometry import create_meshgrid
from kornia.image import draw_convex_polygon, draw_rectangle
from kornia.image.draw import draw_line, draw_point2d
-from testing.base import BaseTester
+from testing.base import BaseTester, dynamo_is_available
class TestDrawPoint(BaseTester):
@@ -61,9 +64,9 @@ class TestDrawPoint(BaseTester):
def test_draw_point2d_with_mismatched_dims(self, dtype, device):
"""Test that we raise if the len of the color tensor != the # of image channels."""
points = torch.tensor([(1, 3), (2, 4)], device=device)
- color = torch.tensor([100], dtype=dtype, device=device)
+ color = torch.tensor([100, 50], dtype=dtype, device=device)
img = torch.zeros(3, 8, 8, dtype=dtype, device=device)
- with pytest.raises(Exception):
+ with pytest.raises(BaseError, match="Color dim must match"):
draw_point2d(img, points, color)
def test_draw_point2d_with_mismatched_dtype(self, device):
@@ -145,10 +148,56 @@ class TestDrawPoint(BaseTester):
out = draw_point2d(img, torch.tensor([[1, 1]], device=device), torch.tensor(9, dtype=dtype, device=device))
assert out[..., 1, 1].flatten().tolist() == [9.0]
- def test_draw_point2d_0d_color_on_multichannel_image_fails_the_channel_check(self, dtype, device):
- img = torch.zeros(3, 4, 4, dtype=dtype, device=device)
- with pytest.raises(BaseError, match="Color dim must match"):
- draw_point2d(img, torch.tensor([[1, 1]], device=device), torch.tensor(9, dtype=dtype, device=device))
+ @pytest.mark.parametrize("color", [torch.tensor([7.0]), torch.tensor(7.0)])
+ def test_draw_point2d_single_value_color_fills_every_channel(self, color, dtype, device):
+ img = torch.zeros(3, 4, 5, dtype=dtype, device=device)
+ out = draw_point2d(img, torch.tensor([[1, 2]], device=device), color.to(device))
+ assert out[:, 2, 1].tolist() == [7.0, 7.0, 7.0]
+ assert int(out.count_nonzero()) == 3
+
+ def test_draw_point2d_rejects_a_batched_image(self, dtype, device):
+ img = torch.zeros(1, 3, 4, 5, dtype=dtype, device=device)
+ with pytest.raises(ValueError, match=r"\(C, H, W\)"):
+ draw_point2d(img, torch.tensor([[1, 2]], device=device), torch.tensor([1.0], device=device))
+
+ def test_draw_point2d_negative_coordinate_raises(self, dtype, device):
+ img = torch.zeros(1, 3, 4, dtype=dtype, device=device) # H = 3, W = 4
+ with pytest.raises(ValueError, match="inside"):
+ draw_point2d(img, torch.tensor([[-1, 0]], device=device), torch.tensor([1.0], device=device))
+ assert img.sum() == 0 # nothing drawn, in particular not in the last column
+
+ def test_draw_point2d_rounds_to_the_nearest_pixel_centre(self, dtype, device):
+ img = torch.zeros(3, 4, dtype=dtype, device=device)
+ draw_point2d(img, torch.tensor([[2.7, 1.6]], device=device), torch.tensor([1.0], device=device))
+ assert img.nonzero().tolist() == [[2, 3]] # (y, x): x 2.7 -> 3, y 1.6 -> 2
+
+ @pytest.mark.parametrize(("x", "pixel"), [(-0.4, 0), (-0.5, 0), (0.5, 1), (1.5, 2), (2.5, 3)])
+ def test_halfway_and_slightly_negative_coordinates(self, x, pixel, dtype, device):
+ img = torch.zeros(3, 4, dtype=dtype, device=device)
+ draw_point2d(img, torch.tensor([[x, 0.0]], device=device), torch.tensor([1.0], device=device))
+ assert img[0].nonzero().flatten().tolist() == [pixel]
+
+ @pytest.mark.parametrize("x", [129, 255])
+ def test_half_precision_points_round_in_float32(self, x, device):
+ # bfloat16 cannot represent x + 0.5 for x >= 128: 129 + 0.5 -> 130 and 255 + 0.5 -> 256 (a spurious ValueError)
+ img = torch.zeros(1, 3, 256, device=device)
+ points = torch.tensor([[x, 0]], dtype=torch.bfloat16, device=device)
+ draw_point2d(img, points, torch.tensor([1.0], device=device))
+ assert img[0, 0].nonzero().flatten().tolist() == [x]
+
+ @pytest.mark.parametrize("point", [(-0.6, 0.0), (3.5, 0.0), (0.0, -0.6), (0.0, 2.5)])
+ def test_draw_point2d_just_outside_after_rounding_raises(self, point, dtype, device):
+ img = torch.zeros(3, 4, dtype=dtype, device=device) # H = 3, W = 4: x 3.5 and y 2.5 round to just outside
+ with pytest.raises(ValueError, match="inside"):
+ draw_point2d(img, torch.tensor([point], device=device), torch.tensor([1.0], device=device))
+
+ def test_float64_points_on_the_cpu_draw_on_the_image_device(self, device):
+ # torch.from_numpy gives float64 points on the CPU; MPS has no float64, so they are rounded before they move
+ img = torch.zeros(3, 4, 5, device=device)
+ points = torch.tensor([[1.4, 2.6], [3.0, 0.0]], dtype=torch.float64)
+ draw_point2d(img, points, torch.tensor([1.0, 0.5, 0.25]))
+ assert img[0].nonzero().tolist() == [[0, 3], [3, 1]] # (row, col): x 1.4 -> 1, y 2.6 -> 3
+ assert img[:, 3, 1].tolist() == [1.0, 0.5, 0.25]
class TestDrawLine(BaseTester):
@@ -208,14 +257,15 @@ class TestDrawLine(BaseTester):
"""Test drawing a line with m <= -1."""
img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
img = draw_line(img, torch.tensor([0, 7]), torch.tensor([6, 0]), torch.tensor([255]))
+ # Literal = 255 * cv2.line(np.zeros((8, 8), np.uint8), (0, 7), (6, 0), 1, 1, cv2.LINE_8) (OpenCV 5.0).
img_mask = torch.tensor(
[
[
- [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 255.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 255.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 255.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 255.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 255.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 255.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 255.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 255.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[255.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
@@ -230,13 +280,14 @@ class TestDrawLine(BaseTester):
"""Test drawing a line with -1 < m < 0."""
img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
img = draw_line(img, torch.tensor([1, 5]), torch.tensor([7, 0]), torch.tensor([255]))
+ # Literal = 255 * cv2.line(np.zeros((8, 8), np.uint8), (1, 5), (7, 0), 1, 1, cv2.LINE_8) (OpenCV 5.0).
img_mask = torch.tensor(
[
[
- [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 255.0, 255.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 255.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 255.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 255.0, 0.0, 0.0],
- [0.0, 0.0, 0.0, 0.0, 255.0, 0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0, 255.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 255.0, 255.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 255.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 255.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
@@ -252,12 +303,13 @@ class TestDrawLine(BaseTester):
"""Test drawing a line with 0 < m < 1."""
img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
img = draw_line(img, torch.tensor([0, 0]), torch.tensor([6, 2]), torch.tensor([255]))
+ # Literal = 255 * cv2.line(np.zeros((8, 8), np.uint8), (0, 0), (6, 2), 1, 1, cv2.LINE_8) (OpenCV 5.0).
img_mask = torch.tensor(
[
[
- [255.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- [0.0, 255.0, 255.0, 255.0, 0.0, 0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0, 0.0, 255.0, 255.0, 255.0, 0.0],
+ [255.0, 255.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 255.0, 255.0, 255.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 255.0, 255.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
@@ -274,6 +326,7 @@ class TestDrawLine(BaseTester):
"""Test drawing a line with m >= 1."""
img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
img = draw_line(img, torch.tensor([3, 7]), torch.tensor([1, 4]), torch.tensor([255]))
+ # Literal = 255 * cv2.line(np.zeros((8, 8), np.uint8), (3, 7), (1, 4), 1, 1, cv2.LINE_8) (OpenCV 5.0).
img_mask = torch.tensor(
[
[
@@ -282,7 +335,7 @@ class TestDrawLine(BaseTester):
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 255.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- [0.0, 255.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 255.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 255.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 255.0, 0.0, 0.0, 0.0, 0.0],
]
@@ -298,17 +351,19 @@ class TestDrawLine(BaseTester):
img = draw_line(
img, torch.tensor([[0, 7], [0, 7], [0, 2]]), torch.tensor([[6, 0], [0, 0], [7, 7]]), torch.tensor([255])
)
+ # Lines 1 and 3 equal cv2.line(np.zeros((8, 8), np.uint8), p1, p2, 1, 1, cv2.LINE_8) * 255 (OpenCV 5.0) for
+ # (0, 7)->(6, 0) and (0, 2)->(7, 7); line 2 is the vertical x = 0.
img_mask = torch.tensor(
[
[
- [255.0, 0.0, 0.0, 0.0, 0.0, 0.0, 255.0, 0.0],
[255.0, 0.0, 0.0, 0.0, 0.0, 0.0, 255.0, 0.0],
[255.0, 0.0, 0.0, 0.0, 0.0, 255.0, 0.0, 0.0],
- [255.0, 255.0, 0.0, 0.0, 255.0, 0.0, 0.0, 0.0],
- [255.0, 0.0, 255.0, 255.0, 0.0, 0.0, 0.0, 0.0],
- [255.0, 0.0, 255.0, 255.0, 255.0, 0.0, 0.0, 0.0],
- [255.0, 255.0, 0.0, 0.0, 0.0, 255.0, 0.0, 0.0],
- [255.0, 0.0, 0.0, 0.0, 0.0, 0.0, 255.0, 255.0],
+ [255.0, 0.0, 0.0, 0.0, 255.0, 0.0, 0.0, 0.0],
+ [255.0, 255.0, 255.0, 255.0, 0.0, 0.0, 0.0, 0.0],
+ [255.0, 0.0, 0.0, 255.0, 0.0, 0.0, 0.0, 0.0],
+ [255.0, 0.0, 255.0, 0.0, 255.0, 0.0, 0.0, 0.0],
+ [255.0, 255.0, 0.0, 0.0, 0.0, 255.0, 255.0, 0.0],
+ [255.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 255.0],
]
],
device=device,
@@ -355,7 +410,9 @@ class TestDrawLine(BaseTester):
assert "image must have 3 dimensions (C,H,W)." == str(excinfo.value)
- @pytest.mark.parametrize("img_size,color", [((1, 8, 8), torch.tensor([23, 53])), ((3, 8, 8), torch.tensor([255]))])
+ @pytest.mark.parametrize(
+ "img_size,color", [((1, 8, 8), torch.tensor([23, 53])), ((3, 8, 8), torch.tensor([23, 53]))]
+ )
def test_color_image_channel_size(self, img_size, color, dtype, device):
img = torch.zeros(*img_size, dtype=dtype, device=device)
with pytest.raises(ValueError) as excinfo:
@@ -432,14 +489,83 @@ class TestDrawLine(BaseTester):
expected = draw_line(expected, a, b, color)
self.assert_close(batched, expected, rtol=0.0, atol=0.0)
+ @pytest.mark.parametrize("color", [torch.tensor([7.0]), torch.tensor(7.0)])
+ def test_draw_line_single_value_color_fills_every_channel(self, color, dtype, device):
+ img = torch.zeros(3, 4, 5, dtype=dtype, device=device)
+ out = draw_line(img, torch.tensor([0, 1], device=device), torch.tensor([3, 1], device=device), color.to(device))
+ assert out[:, 1, :4].tolist() == [[7.0] * 4] * 3
+ assert int(out.count_nonzero()) == 12
+
+ def test_draw_line_is_the_same_in_both_directions(self, dtype, device):
+ p, q = torch.tensor([0, 0], device=device), torch.tensor([4, 1], device=device)
+ a = draw_line(torch.zeros(1, 3, 6, dtype=dtype, device=device), p, q, torch.tensor([1.0], device=device))
+ b = draw_line(torch.zeros(1, 3, 6, dtype=dtype, device=device), q, p, torch.tensor([1.0], device=device))
+ self.assert_close(a, b)
+
+ def test_draw_line_pixels_are_nearest_to_the_segment(self, dtype, device):
+ # (0, 0) -> (4, 1) on 3x6: the ideal row is x / 4, so columns 0, 1 -> row 0, columns 3, 4 -> row 1 and the
+ # tie at column 2 (y = 0.5) rounds up to row 1. OpenCV 5.0 rounds that tie down:
+ # cv2.line(np.zeros((3, 6), np.uint8), (0, 0), (4, 1), 1, 1, cv2.LINE_8) returns
+ # [[1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0]].
+ img = draw_line(
+ torch.zeros(1, 3, 6, dtype=dtype, device=device),
+ torch.tensor([0, 0], device=device),
+ torch.tensor([4, 1], device=device),
+ torch.tensor([1.0], device=device),
+ )
+ expected = torch.tensor(
+ [[[1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0]]], dtype=dtype, device=device
+ )
+ self.assert_close(img, expected, rtol=0.0, atol=0.0)
+
def test_draw_line_accepts_0d_scalar_color(self, dtype, device):
# torch.tensor(255) is a natural grayscale color; color.size(0) used to IndexError.
img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
out = draw_line(img, torch.tensor([1, 4]), torch.tensor([6, 4]), torch.tensor(255, dtype=dtype, device=device))
assert out[0, 4, 1:7].tolist() == [255.0] * 6
+ def test_draw_line_rounds_fractional_endpoints(self, dtype, device):
+ img = torch.zeros(1, 3, 6, dtype=dtype, device=device)
+ draw_line(
+ img,
+ torch.tensor([0.6, 1.0], device=device),
+ torch.tensor([3.4, 1.0], device=device),
+ torch.tensor([1.0], device=device),
+ )
+ assert img[0, 1].tolist() == [0, 1, 1, 1, 0, 0]
+
+ def test_half_precision_endpoints_round_in_float32(self, device):
+ # float16 spacing is 1 above 1024, so 1027 + 0.5 would round to 1028 and 1025 + 0.5 to 1026
+ img = torch.zeros(1, 3, 1030, device=device)
+ p1 = torch.tensor([1025.0, 1.0], dtype=torch.float16, device=device)
+ p2 = torch.tensor([1027.0, 1.0], dtype=torch.float16, device=device)
+ draw_line(img, p1, p2, torch.tensor([1.0], device=device))
+ assert img[0, 1].nonzero().flatten().tolist() == [1025, 1026, 1027]
+
+ def test_float64_endpoints_on_the_cpu_draw_on_the_image_device(self, device):
+ # torch.from_numpy gives float64 points on the CPU; MPS has no float64, so they are rounded before they move
+ img = torch.zeros(1, 4, 6, device=device)
+ p1 = torch.tensor([0.4, 2.6], dtype=torch.float64)
+ p2 = torch.tensor([4.6, 2.6], dtype=torch.float64)
+ draw_line(img, p1, p2, torch.tensor([1.0]))
+ assert img[0].nonzero().tolist() == [[3, 0], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5]]
+
+ def test_draw_line_endpoint_rounding_outside_raises(self, dtype, device):
+ img = torch.zeros(1, 3, 6, dtype=dtype, device=device)
+ with pytest.raises(ValueError, match="p2 is out of bounds"):
+ draw_line(
+ img,
+ torch.tensor([0.0, 1.0], device=device),
+ torch.tensor([5.5, 1.0], device=device),
+ torch.tensor([1.0], device=device),
+ )
+
class TestDrawRectangle(BaseTester):
+ def test_rejects_an_image_without_a_batch_axis(self, device):
+ with pytest.raises(ShapeError):
+ draw_rectangle(torch.zeros(3, 6, 5, device=device), torch.tensor([[[0, 0, 2, 2]]], device=device))
+
@pytest.mark.parametrize("batch", [4, 17])
@pytest.mark.parametrize("color", [torch.Tensor([1.0]), torch.Tensor([0.5])])
def test_smoke(self, device, batch, color):
@@ -468,8 +594,8 @@ class TestDrawRectangle(BaseTester):
if fill:
assert image_w_rectangle.sum() == batch * 3 * height * width
else:
- # corners are double counted
- assert image_w_rectangle.sum() == batch * 3 * (2 * height + 2 * width - 4)
+ # the right side (x = width) and bottom side (y = height) lie outside the image and are not drawn
+ assert image_w_rectangle.sum() == batch * 3 * (height + width - 1)
@pytest.mark.parametrize("batch", [4, 6])
@pytest.mark.parametrize("N", [5, 12])
@@ -595,8 +721,132 @@ class TestDrawRectangle(BaseTester):
self.assert_close(out, expected)
assert out.count_nonzero() > 0
+ def test_reversed_corners_draw_the_same_rectangle(self, device):
+ a = draw_rectangle(
+ torch.zeros(1, 1, 5, 6, device=device), torch.tensor([[[1, 1, 3, 2]]], device=device), torch.tensor([1.0])
+ )
+ b = draw_rectangle(
+ torch.zeros(1, 1, 5, 6, device=device), torch.tensor([[[3, 2, 1, 1]]], device=device), torch.tensor([1.0])
+ )
+ assert a.sum() > 0
+ self.assert_close(a, b)
+
+ def test_sides_outside_the_image_are_not_drawn(self, device):
+ out = draw_rectangle(
+ torch.zeros(1, 1, 5, 6, device=device),
+ torch.tensor([[[-2, -2, 10, 10]]], device=device),
+ torch.tensor([1.0]),
+ )
+ assert out.sum() == 0 # every side lies outside the 5x6 image
+
+ def test_partly_outside_box_draws_only_its_inside_sides(self, device):
+ out = draw_rectangle(
+ torch.zeros(1, 1, 5, 6, device=device), torch.tensor([[[2, 1, 9, 3]]], device=device), torch.tensor([1.0])
+ )
+ expected = torch.zeros(5, 6, device=device)
+ expected[1, 2:] = 1 # top side, clipped at the right border
+ expected[3, 2:] = 1 # bottom side
+ expected[1:4, 2] = 1 # left side; the right side (x = 9) is outside and not drawn
+ self.assert_close(out[0, 0], expected)
+
+ def test_fill_is_clipped_to_the_image(self, device):
+ out = draw_rectangle(
+ torch.zeros(1, 1, 5, 6, device=device),
+ torch.tensor([[[-2, 3, 2, 9]]], device=device),
+ torch.tensor([1.0]),
+ fill=True,
+ )
+ expected = torch.zeros(5, 6, device=device)
+ expected[3:, :3] = 1
+ self.assert_close(out[0, 0], expected)
+
+ def test_rectangle_rounds_fractional_corners(self, device):
+ out = draw_rectangle(
+ torch.zeros(1, 1, 5, 6, device=device),
+ torch.tensor([[[0.6, 0.6, 2.4, 2.6]]], device=device),
+ torch.tensor([1.0]),
+ fill=True,
+ )
+ expected = torch.zeros(5, 6, device=device)
+ expected[1:4, 1:3] = 1 # x 0.6..2.4 -> 1..2, y 0.6..2.6 -> 1..3
+ self.assert_close(out[0, 0], expected)
+
+ @pytest.mark.parametrize(("rectangle", "match"), [(torch.zeros(2, 1, 4), "batch"), (torch.zeros(1, 1, 3), "4")])
+ def test_invalid_rectangle_raises_value_error(self, rectangle, match, device):
+ with pytest.raises(ValueError, match=match):
+ draw_rectangle(torch.zeros(1, 1, 5, 6, device=device), rectangle.to(device))
+
+ def test_full_frame_inside_the_image(self, device):
+ batch, height, width = 2, 7, 9
+ black_image = torch.zeros(batch, 3, height, width, device=device)
+ points = torch.tensor([0, 0, width - 1, height - 1]).to(device).expand(batch, 1, 4)
+ out = draw_rectangle(black_image, points, color=torch.tensor([1.0]))
+ assert out.sum() == batch * 3 * (2 * height + 2 * width - 4)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.skipif(not dynamo_is_available(), reason="torch.export needs Dynamo on this torch/python pair")
+ @pytest.mark.skipif(
+ not torch_version_ge(2, 14),
+ reason="slices with data-dependent bounds export from torch 2.14 (2.9.1 fails to export, 2.6 bakes the input)",
+ )
+ @pytest.mark.parametrize("fill", [False, True])
+ def test_onnx_export_draws_the_rectangles_given_at_run_time(self, fill):
+ pytest.importorskip("onnx")
+ pytest.importorskip("onnxscript")
+ ort = pytest.importorskip("onnxruntime")
+
+ class Draw(torch.nn.Module):
+ def forward(self, image, rectangle, color):
+ return draw_rectangle(image.clone(), rectangle, color, fill=fill)
+
+ model = Draw()
+ image = torch.zeros(1, 3, 6, 9)
+ color = torch.tensor([1.0, 0.5, 0.2])
+ traced_on = torch.tensor([[[1.0, 1.0, 4.0, 3.0], [2.0, 0.0, 7.0, 5.0]]])
+ buffer = io.BytesIO()
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ torch.onnx.export(model, (image, traced_on, color), dynamo=True, opset_version=18, verbose=False).save(
+ buffer
+ )
+ session = ort.InferenceSession(buffer.getvalue(), providers=["CPUExecutionProvider"])
+ names = [i.name for i in session.get_inputs()]
+ assert len(names) == 3 # the rectangle stays a graph input, not a constant
+ # rectangles other than the traced ones: reversed and fractional corners, sides and whole boxes outside
+ for rectangle in (
+ traced_on,
+ torch.tensor([[[7.0, 4.0, 2.0, 1.0], [-3.0, 2.4, 3.6, 12.0]]]),
+ torch.tensor([[[20.0, 20.0, 30.0, 30.0], [-5.0, -5.0, 0.4, 0.6]]]),
+ torch.tensor([[[0.0, 0.0, 8.0, 5.0], [8.0, 5.0, 8.0, 5.0]]]),
+ ):
+ feeds = dict(zip(names, (image.numpy(), rectangle.numpy(), color.numpy())))
+ got = torch.from_numpy(session.run(None, feeds)[0])
+ self.assert_close(got, model(image, rectangle, color), rtol=0, atol=0)
+
class TestFillConvexPolygon(BaseTester):
+ @pytest.mark.parametrize("vertex_dtype", [torch.float32, torch.bfloat16, torch.float16])
+ def test_edge_maths_does_not_depend_on_the_vertex_dtype(self, vertex_dtype, device, dtype):
+ # vertices 260 and 280 are exact in bfloat16; the fill must be columns 260..280 (21 px) in every row
+ poly = torch.tensor([[[260.0, 0.0], [280.0, 0.0], [280.0, 5.0], [260.0, 5.0]]], device=device).to(vertex_dtype)
+ img = draw_convex_polygon(
+ torch.zeros(1, 1, 6, 300, device=device, dtype=dtype), poly, torch.tensor([1.0], device=device, dtype=dtype)
+ )
+ assert img[0, 0, 2].nonzero().flatten()[[0, -1]].tolist() == [260, 280]
+ assert int(img[0, 0, 2].sum()) == 21
+
+ def test_centre_exactly_on_a_sloped_edge_is_filled(self, device, dtype):
+ # hull [[13,18],[48,1],[12,31],[12,22]] on 31x47: (row 26, col 18) lies on edge (48,1)->(12,31)
+ poly = torch.tensor([[[13.0, 18.0], [48.0, 1.0], [12.0, 31.0], [12.0, 22.0]]], device=device)
+ img = draw_convex_polygon(torch.zeros(1, 1, 31, 47, device=device), poly, torch.tensor([1.0], device=device))
+ assert img[0, 0, 26, 18] == 1
+
+ def test_long_shallow_edge_with_vertices_outside_the_image(self, device, dtype):
+ # triangle (-100,0),(100,4),(-100,4) on 5x6 covers 13 pixel centres (rows 2-4)
+ poly = torch.tensor([[[-100.0, 0.0], [100.0, 4.0], [-100.0, 4.0]]], device=device)
+ img = draw_convex_polygon(torch.zeros(1, 1, 5, 6, device=device), poly, torch.tensor([1.0], device=device))
+ assert int(img.sum()) == 13
+
def test_circle(self, device, dtype):
b, c, h, w = 1, 3, 500, 500
n = 5000
@@ -753,3 +1003,20 @@ class TestFillConvexPolygon(BaseTester):
expected = draw_convex_polygon(im.clone(), square, torch.tensor([9.0], device=device, dtype=dtype))
self.assert_close(out, expected)
assert out.count_nonzero() > 0
+
+ def test_uint8_image_takes_a_float_colour(self, device):
+ img = torch.full((1, 3, 5, 7), 9, dtype=torch.uint8, device=device)
+ poly = torch.tensor([[[1.0, 1.0], [5.0, 1.0], [5.0, 3.0], [1.0, 3.0]]], device=device)
+ draw_convex_polygon(img, poly, torch.tensor([[200.0, 100.0, 50.0]], device=device))
+ assert img.dtype == torch.uint8
+ assert img[0, :, 2, 3].tolist() == [200, 100, 50] # inside: the colour, cast to uint8
+ assert img[0, :, 4, 6].tolist() == [9, 9, 9] # outside: unchanged
+ assert int((img[0, 0] == 200).sum()) == 15 # rows 1-3, columns 1-5
+
+ def test_nan_pixel_inside_the_polygon_is_overwritten(self, device, dtype):
+ img = torch.zeros(1, 1, 5, 6, device=device, dtype=dtype)
+ img[0, 0, 2, 2] = float("nan")
+ poly = torch.tensor([[[1.0, 1.0], [4.0, 1.0], [4.0, 3.0], [1.0, 3.0]]], device=device, dtype=dtype)
+ draw_convex_polygon(img, poly, torch.tensor([1.0], device=device, dtype=dtype))
+ assert img[0, 0, 2, 2].item() == 1.0
+ assert not img.isnan().any()
diff --git a/tests/image/test_image.py b/tests/image/test_image.py
index cfbd5fe37..e5f2970d9 100644
--- a/tests/image/test_image.py
+++ b/tests/image/test_image.py
@@ -22,10 +22,12 @@ import pytest
import torch
from kornia.core._compat import torch_version_le
-from kornia.core.exceptions import ShapeError
-from kornia.image.base import KORNIA_CHECK_IMAGE_LAYOUT, ChannelsOrder, ColorSpace, ImageLayout, ImageSize, PixelFormat
+from kornia.core.exceptions import ShapeError, ValueCheckError
+from kornia.image import ColorSpace
+from kornia.image.base import KORNIA_CHECK_IMAGE_LAYOUT, ChannelsOrder, ImageLayout, ImageSize, PixelFormat
from kornia.image.image import Image
from kornia.image.image_print import image_to_string
+from kornia.io import ImageLoadType, load_image
from testing.base import BaseTester
@@ -194,13 +196,109 @@ class TestImage(BaseTester):
img = Image.from_numpy(data, color_space=ColorSpace.RGB, channels_order=ChannelsOrder.CHANNELS_LAST)
img.write(tmp_path / "image.jpg")
+ def test_to_returns_a_new_image_and_leaves_the_original(self, device):
+ img = Image.from_numpy(np.zeros((4, 5, 3), dtype=np.uint8))
+ out = img.to(device, torch.float32)
+ assert out is not img
+ assert img.dtype == torch.uint8
+ assert img.pixel_format.bit_depth == 8
+ assert out.dtype == torch.float32
+ assert out.device == device
+ assert out.pixel_format.bit_depth == 32
+ assert out.clone().pixel_format.bit_depth == 32 # bit_depth follows the dtype, so clone() passes the check
+
+ def test_float_leaves_the_original(self):
+ img = Image.from_numpy(np.zeros((4, 5, 3), dtype=np.uint8))
+ out = img.float()
+ assert img.dtype == torch.uint8
+ assert out.dtype == torch.float32
+ assert out.pixel_format.bit_depth == 32
+
+ @pytest.mark.parametrize("order", [ChannelsOrder.CHANNELS_LAST, ChannelsOrder.CHANNELS_FIRST])
+ def test_from_numpy_accepts_a_2d_gray_array(self, order):
+ data = np.arange(20, dtype=np.uint8).reshape(4, 5) # H = 4, W = 5
+ img = Image.from_numpy(data, color_space=ColorSpace.GRAY, channels_order=order)
+ assert (img.channels, img.height, img.width) == (1, 4, 5)
+ data[0, 1] = 99
+ assert int(img.data.flatten()[1]) == 99 # shares memory, like a 3-D array
+
+ def test_write_stores_true_colours_for_a_bgr_image(self, tmp_path):
+ bgr = np.zeros((4, 5, 3), dtype=np.uint8)
+ bgr[..., 0], bgr[..., 1], bgr[..., 2] = 2, 1, 0 # B, G, R -> true RGB (0, 1, 2)
+ Image.from_numpy(bgr, color_space=ColorSpace.BGR).write(str(tmp_path / "bgr.png"))
+ assert load_image(tmp_path / "bgr.png", ImageLoadType.RGB8)[:, 0, 0].tolist() == [0, 1, 2]
+
+ def test_print_shows_true_colours_for_a_bgr_image(self, capsys):
+ rgb = torch.zeros(3, 2, 3, dtype=torch.uint8)
+ rgb[0] = 255 # red
+ make_image(rgb.flip(0).permute(1, 2, 0).contiguous(), ColorSpace.BGR, ChannelsOrder.CHANNELS_LAST).print()
+ assert capsys.readouterr().out == image_to_string(rgb) + "\n"
+
+ @pytest.mark.parametrize(
+ ("cs", "channels"), [(ColorSpace.GRAY, 3), (ColorSpace.RGB, 1), (ColorSpace.BGR, 4), (ColorSpace.RGB, 4)]
+ )
+ def test_color_space_must_match_the_channel_count(self, cs, channels):
+ with pytest.raises(ValueCheckError, match="color space"):
+ make_image(torch.zeros(4, 5, channels, dtype=torch.uint8), cs, ChannelsOrder.CHANNELS_LAST)
+
+ def test_unknown_color_space_accepts_any_channel_count(self):
+ img = make_image(torch.zeros(4, 5, 4, dtype=torch.uint8), ColorSpace.UNKNOWN, ChannelsOrder.CHANNELS_LAST)
+ assert img.channels == 4
+
+ def test_from_numpy_infers_the_color_space(self):
+ assert Image.from_numpy(np.zeros((4, 5, 1), dtype=np.uint8)).pixel_format.color_space == ColorSpace.GRAY
+ assert Image.from_numpy(np.zeros((4, 5), dtype=np.uint8)).pixel_format.color_space == ColorSpace.GRAY
+ assert Image.from_numpy(np.zeros((4, 5, 3), dtype=np.uint8)).pixel_format.color_space == ColorSpace.RGB
+ assert Image.from_numpy(np.zeros((4, 5, 4), dtype=np.uint8)).pixel_format.color_space == ColorSpace.UNKNOWN
+
+ def test_from_numpy_rejects_a_mismatching_color_space(self):
+ with pytest.raises(ValueCheckError, match="color space"):
+ Image.from_numpy(np.zeros((4, 5, 1), dtype=np.uint8), color_space=ColorSpace.RGB)
+
+ def test_from_dlpack_infers_the_color_space(self):
+ gray = Image.from_dlpack(np.zeros((1, 4, 5), dtype=np.uint8).__dlpack__())
+ assert gray.pixel_format.color_space == ColorSpace.GRAY
+ multi = Image.from_dlpack(np.zeros((4, 4, 5), dtype=np.uint8).__dlpack__())
+ assert multi.pixel_format.color_space == ColorSpace.UNKNOWN
+
+ @pytest.mark.parametrize(
+ ("dtype", "bits", "ok"),
+ [(torch.uint8, 8, True), (torch.uint8, 12, False), (torch.uint16, 16, True), (torch.uint16, 12, False)],
+ )
+ def test_bit_depth_is_the_storage_bits(self, dtype, bits, ok):
+ data = torch.zeros(3, 4, 5, dtype=dtype)
+ pf = PixelFormat(color_space=ColorSpace.RGB, bit_depth=bits)
+ layout = ImageLayout(ImageSize(4, 5), 3, ChannelsOrder.CHANNELS_FIRST)
+ if ok:
+ assert Image(data, pf, layout).pixel_format.bit_depth == bits
+ else:
+ with pytest.raises(ValueCheckError, match="bit depth"):
+ Image(data, pf, layout)
+
+ def test_pixel_format_checks_follow_disable_checks(self):
+ from kornia.core.check import disable_checks, enable_checks
+
+ layout = ImageLayout(ImageSize(4, 5), 1, ChannelsOrder.CHANNELS_FIRST)
+ disable_checks()
+ try:
+ img = Image(torch.zeros(1, 4, 5, dtype=torch.uint8), PixelFormat(ColorSpace.RGB, 12), layout)
+ finally:
+ enable_checks()
+ assert img.pixel_format.bit_depth == 12
+
+ def test_color_space_is_exported(self):
+ import kornia.image
+
+ assert kornia.image.ColorSpace is ColorSpace
+ assert "ColorSpace" in kornia.image.__all__
+
@pytest.mark.parametrize("order", [ChannelsOrder.CHANNELS_LAST, ChannelsOrder.CHANNELS_FIRST])
@pytest.mark.parametrize("height", [4, 3])
def test_print_renders_the_channels_first_image(self, device, order, height, capsys) -> None:
chw = (torch.arange(3 * height * 5, device=device).reshape(3, height, 5) * 4).to(torch.uint8)
data = chw.permute(1, 2, 0).contiguous() if order == ChannelsOrder.CHANNELS_LAST else chw
make_image(data, ColorSpace.RGB, order).print()
- assert capsys.readouterr().out == image_to_string(chw) + "\n"
+ assert capsys.readouterr().out == image_to_string(chw.cpu()) + "\n" # the CPU result
def make_image(data: torch.Tensor, cs: ColorSpace, order: ChannelsOrder) -> Image:
diff --git a/tests/image/test_image_utils.py b/tests/image/test_image_utils.py
index d7f496b63..fc2442a55 100644
--- a/tests/image/test_image_utils.py
+++ b/tests/image/test_image_utils.py
@@ -275,3 +275,21 @@ def test_make_grid_valid(device, dtype, n_row):
assert actual.dtype == tensor.dtype
assert actual.device == tensor.device
assert_close(actual, expected)
+
+
+def test_tensor_to_image_bfloat16_becomes_float32():
+ out = kornia.image.tensor_to_image(torch.full((3, 4, 5), 0.5, dtype=torch.bfloat16))
+ assert out.dtype == np.float32
+ assert out.shape == (4, 5, 3)
+ assert (out == 0.5).all()
+
+
[email protected]("bad", [torch.zeros(4, 5, 3), [[0, 1], [2, 3]]])
+def test_image_to_tensor_rejects_a_non_ndarray(bad):
+ with pytest.raises(TypeError, match="numpy"):
+ kornia.image.image_to_tensor(bad)
+
+
+def test_make_grid_rejects_negative_padding():
+ with pytest.raises(ValueError, match="padding"):
+ kornia.image.make_grid(torch.zeros(4, 1, 3, 5), padding=-1)
diff --git a/tests/image/test_print.py b/tests/image/test_print.py
index 5e4ed91ca..a86274e28 100644
--- a/tests/image/test_print.py
+++ b/tests/image/test_print.py
@@ -15,10 +15,13 @@
# limitations under the License.
#
+import os
+
import pytest
import torch
-from kornia.image import image_to_string, print_image
+from kornia.image import image_print, image_to_string, print_image
+from kornia.io import write_image
class TestImageToString:
@@ -34,11 +37,17 @@ class TestImageToString:
image = torch.arange(16).reshape(1, 4, 4).repeat(3, 1, 1).long() * 16
out = image_to_string(image)
+ # nearest of the 240 fixed colours for the grays 0, 16, ..., 240 (code 59 = #5f5f5f and 145 = #afafaf are
+ # cube colours that are nearer than any ramp gray); generated with
+ # from kornia.image.image_print import SHORT2RGB_DICT
+ # rgb = {c: [int(SHORT2RGB_DICT[str(c)][i : i + 2], 16) for i in (0, 2, 4)] for c in range(16, 256)}
+ # [min(rgb, key=lambda c: sum((a - 16 * i) ** 2 for a in rgb[c])) for i in range(16)]
+ # (min takes the lowest code on a tie, as image_to_string does)
expected = (
- "\033[48;5;16m \033[48;5;16m \033[48;5;16m \033[48;5;59m \033[0m\n"
- "\033[48;5;59m \033[48;5;59m \033[48;5;59m \033[48;5;59m \033[0m\n"
- "\033[48;5;102m \033[48;5;102m \033[48;5;145m \033[48;5;145m \033[0m\n"
- "\033[48;5;145m \033[48;5;188m \033[48;5;188m \033[48;5;231m \033[0m\n"
+ "\033[48;5;16m \033[48;5;233m \033[48;5;234m \033[48;5;236m \033[0m\n"
+ "\033[48;5;238m \033[48;5;239m \033[48;5;59m \033[48;5;242m \033[0m\n"
+ "\033[48;5;244m \033[48;5;246m \033[48;5;247m \033[48;5;145m \033[0m\n"
+ "\033[48;5;250m \033[48;5;252m \033[48;5;254m \033[48;5;255m \033[0m\n"
)
assert out == expected
@@ -76,7 +85,7 @@ class TestImageToString:
image_to_string(img)
assert "Value range mismatch" in str(errinfo.value) or "Invalid image value range" in str(errinfo.value)
- with pytest.raises(RuntimeError):
+ with pytest.raises(TypeError):
print_image([img]) # Do not accept list
def test_rejects_a_tensor_that_is_not_a_color_or_gray_image(self):
@@ -88,3 +97,79 @@ class TestImageToString:
def test_print_smoke(self):
img = torch.rand(3, 15, 15)
print_image(img)
+
+
+class TestNearestXterm:
+ # Expected codes generated with the snippet in TestImageToString.test_value, for the 0-255 pixel value p:
+ # min(rgb, key=lambda c: sum((a - b) ** 2 for a, b in zip(rgb[c], p)))
+ # p = (128,) * 3 -> 244, (91.6,) * 3 -> 59, (91,) * 3 -> 240, (4.49, 4.49, 3.1) -> 232, (4, 4, 3) -> 16
+
+ def test_gray_uses_the_gray_ramp(self):
+ # 128 -> code 244 (#808080, exact) in the gray ramp; the nearest cube colour is code 102 (#878787)
+ out = image_to_string(torch.full((3, 2, 3), 128, dtype=torch.uint8))
+ assert out.count("48;5;244m") == 6
+ assert out.count("\n") == 2
+
+ def test_a_float_level_is_not_truncated(self):
+ # 91.6 levels: the nearest code is 59 (#5f5f5f = 95, 3.4 away), not 240 (#585858 = 88, 3.6 away), which a
+ # level truncated to 91 would pick
+ out = image_to_string(torch.full((3, 2, 3), 91.6 / 255))
+ assert out.count("48;5;59m") == 6
+ assert "48;5;240m" not in out
+
+ def test_a_float_pixel_is_compared_at_its_unrounded_value(self):
+ # (4.49, 4.49, 3.1) levels: code 232 (#080808) is nearer than code 16 (#000000), squared distance 48.65
+ # against 49.93; the pixel rounded to (4, 4, 3) would pick code 16
+ image = (torch.tensor([4.49, 4.49, 3.1]) / 255)[:, None, None].expand(3, 2, 3)
+ out = image_to_string(image)
+ assert out.count("48;5;232m") == 6
+
+ def test_tall_image_equals_its_two_halves(self):
+ # the nearest colours are computed in chunks of pixels; an image taller than one chunk renders exactly like its
+ # halves rendered one after the other, so no pixel is lost or moved at a chunk boundary (mid-row here)
+ width = 250 # below max_width, so nothing is resized
+ height = 2 * (image_print._PIXELS_PER_CHUNK // width + 1)
+ gen = torch.Generator().manual_seed(0)
+ image = torch.randint(0, 256, (3, height, width), generator=gen, dtype=torch.uint8)
+ top, bottom = image[:, : height // 2], image[:, height // 2 :]
+ assert image_to_string(image) == image_to_string(top) + image_to_string(bottom)
+
+ def test_an_image_on_the_device_prints_like_its_cpu_copy(self, device):
+ # the distances run on the CPU in float64, which MPS cannot hold: the pixels move to the CPU before the cast
+ image = torch.randint(0, 256, (3, 4, 5), generator=torch.Generator().manual_seed(0), dtype=torch.uint8)
+ out = image_to_string(image.to(device))
+ assert out == image_to_string(image)
+ assert out.count("48;5;16m") < 20 # not every pixel black
+
+ def test_distances_are_computed_in_bounded_chunks(self, monkeypatch):
+ # no (pixels, 240) distance matrix has more rows than _PIXELS_PER_CHUNK, whatever the image size
+ sizes = []
+ nearest = image_print._nearest_xterm_codes
+
+ def record(rgb):
+ sizes.append(rgb.shape[0])
+ return nearest(rgb)
+
+ monkeypatch.setattr(image_print, "_nearest_xterm_codes", record)
+ image = torch.zeros(3, 2 * (image_print._PIXELS_PER_CHUNK // 250 + 1), 250, dtype=torch.uint8)
+ image_to_string(image)
+ assert max(sizes) <= image_print._PIXELS_PER_CHUNK
+ assert sum(sizes) == image[0].numel()
+
+ def test_print_image_accepts_a_path(self, tmp_path, capsys):
+ write_image(tmp_path / "p.png", torch.zeros(3, 2, 3, dtype=torch.uint8))
+ print_image(tmp_path / "p.png")
+ assert "\x1b[48;5;" in capsys.readouterr().out
+
+ def test_print_image_accepts_a_path_like_returning_bytes(self, tmp_path, capsys):
+ path = tmp_path / "p.png"
+ write_image(path, torch.zeros(3, 2, 3, dtype=torch.uint8))
+
+ class BytesPath(os.PathLike):
+ def __fspath__(self):
+ return os.fsencode(path)
+
+ print_image(BytesPath())
+ out = capsys.readouterr().out
+ assert out.count("\x1b[48;5;16m") == 6 # 2 x 3 black pixels
+ assert out.count("\x1b[0m\n") == 2
diff --git a/tests/models/test_object_detector.py b/tests/models/test_object_detector.py
index 02fe31836..e0e152915 100644
--- a/tests/models/test_object_detector.py
+++ b/tests/models/test_object_detector.py
@@ -29,6 +29,20 @@ from testing.base import BaseTester
class TestObjectDetector(BaseTester):
+ def test_visualize_keeps_a_border_box_four_sided(self, device):
+ detector = kornia.contrib.object_detection.ObjectDetector(
+ torch.nn.Identity(), torch.nn.Identity(), torch.nn.Identity()
+ )
+ h, w = 6, 9
+ # (class, score, x, y, w, h): a detection covering the whole image, so x + w = W and y + h = H
+ detection = torch.tensor([[0.0, 0.9, 0.0, 0.0, float(w), float(h)]], device=device)
+ out = detector.visualize(torch.ones(1, 3, h, w, device=device), [detection])[0]
+ # visualize draws in the default colour, black, on the white image
+ assert (out[:, 0] == 0).all()
+ assert (out[:, h - 1] == 0).all()
+ assert (out[:, :, 0] == 0).all()
+ assert (out[:, :, w - 1] == 0).all()
+
def test_smoke(self, device, dtype):
batch_size = 2
confidence = 0.3