Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

draw_keypoints() float support #8276

Merged
merged 6 commits into from
Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions test/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,24 @@ def test_draw_segmentation_masks(colors, alpha, device):
torch.testing.assert_close(out[:, overlap], interpolated_overlap, rtol=0.0, atol=1.0)


def test_draw_keypoints_dtypes():
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's move that test down below, so that it is located next to the rest of the draw_keypoints tests. Right now it's in the middle of the draw_segmentation_mask tests which is a bit confusing.

image_uint8 = torch.full((3, 100, 100), 0, dtype=torch.uint8)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This image should not be just zeros, otherwise it will be easy to miss subtle bugs. This should be the same as for the other test i.e.:

Suggested change
image_uint8 = torch.full((3, 100, 100), 0, dtype=torch.uint8)
torch.randint(0, 256, size=(3, 100, 100), dtype=torch.uint8)

and in fact you'll see that there's a bug because the test will fail

image_float = to_dtype(image_uint8, torch.float, scale=True)

keypoints_cp = keypoints.clone()

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't seem to be used anywhere

Suggested change
keypoints_cp = keypoints.clone()

out_uint8 = utils.draw_keypoints(image_uint8, keypoints)
out_float = utils.draw_keypoints(image_float, keypoints)

assert out_uint8.dtype == torch.uint8
assert out_uint8 is not image_uint8

assert out_float.is_floating_point()
assert out_float is not image_float

torch.testing.assert_close(out_uint8, to_dtype(out_float, torch.uint8, scale=True), rtol=0, atol=1)


def test_draw_segmentation_masks_dtypes():
num_masks, h, w = 2, 100, 100

Expand Down
16 changes: 10 additions & 6 deletions torchvision/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,13 +336,13 @@ def draw_keypoints(

"""
Draws Keypoints on given RGB image.
The values of the input image should be uint8 between 0 and 255.
The image values should be uint8 in [0, 255] or float in [0, 1].
Keypoints can be drawn for multiple instances at a time.

This method allows that keypoints and their connectivity are drawn based on the visibility of this keypoint.

Args:
image (Tensor): Tensor of shape (3, H, W) and dtype uint8.
image (Tensor): Tensor of shape (3, H, W) and dtype uint8 or float.
keypoints (Tensor): Tensor of shape (num_instances, K, 2) the K keypoint locations for each of the N instances,
in the format [x, y].
connectivity (List[Tuple[int, int]]]): A List of tuple where each tuple contains a pair of keypoints
Expand All @@ -363,16 +363,16 @@ def draw_keypoints(
For more details, see :ref:`draw_keypoints_with_visibility`.

Returns:
img (Tensor[C, H, W]): Image Tensor of dtype uint8 with keypoints drawn.
img (Tensor[C, H, W]): Image Tensor with keypoints drawn.
"""

if not torch.jit.is_scripting() and not torch.jit.is_tracing():
_log_api_usage_once(draw_keypoints)
# validate image
if not isinstance(image, torch.Tensor):
raise TypeError(f"The image must be a tensor, got {type(image)}")
elif image.dtype != torch.uint8:
raise ValueError(f"The image dtype must be uint8, got {image.dtype}")
elif not (image.dtype == torch.uint8 or image.is_floating_point()):
raise ValueError(f"The image dtype must be uint8 or float, got {image.dtype}")
elif image.dim() != 3:
raise ValueError("Pass individual images, not batches")
elif image.size()[0] != 3:
Expand All @@ -397,6 +397,10 @@ def draw_keypoints(
f"Got {visibility.shape = } and {keypoints.shape = }"
)

original_dtype = image.dtype
if image.is_floating_point():
image = (image * 255).to(dtype=torch.uint8)

ndarr = image.permute(1, 2, 0).cpu().numpy()
img_to_draw = Image.fromarray(ndarr)
draw = ImageDraw.Draw(img_to_draw)
Expand Down Expand Up @@ -428,7 +432,7 @@ def draw_keypoints(
width=width,
)

return torch.from_numpy(np.array(img_to_draw)).permute(2, 0, 1).to(dtype=torch.uint8)
return torch.from_numpy(np.array(img_to_draw)).permute(2, 0, 1).to(dtype=original_dtype)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just calling .to here won't scale the float images back down to [0, 1] so we would end up with a flaot image in [0, 255] (that's why the test would fail). It's best to just call to_dtype() for both the uint8 <-> float conversions.



# Flow visualization code adapted from https://github.com/tomrunia/OpticalFlow_Visualization
Expand Down
Loading