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

Visualization support for single channel images #288

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
10 changes: 9 additions & 1 deletion tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@


def test_overlay_mask():
# RGB image
img = Image.fromarray(np.zeros((4, 4, 3)).astype(np.uint8))
mask = Image.fromarray(255 * np.ones((4, 4)).astype(np.uint8))

overlayed = utils.overlay_mask(img, mask, alpha=0.7)

# Check object type
Expand All @@ -16,3 +16,11 @@ def test_overlay_mask():
assert np.all(np.asarray(overlayed)[..., 0] == 0)
assert np.all(np.asarray(overlayed)[..., 1] == 0)
assert np.all(np.asarray(overlayed)[..., 2] == 39)

# grayscale image
img = Image.fromarray(np.zeros((4, 4)).astype(np.uint8))
mask = Image.fromarray(255 * np.ones((4, 4)).astype(np.uint8))
overlayed = utils.overlay_mask(img, mask, alpha=0.7)

# Verify value
assert np.all(np.asarray(overlayed) == 39)
9 changes: 8 additions & 1 deletion torchcam/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,16 @@ def overlay_mask(img: Image, mask: Image, colormap: str = "jet", alpha: float =
if not isinstance(alpha, float) or alpha < 0 or alpha >= 1:
raise ValueError("alpha argument is expected to be of type float between 0 and 1")

if len(img.getbands()) not in {1, 3}:
raise ValueError("img argument needs to be a grayscale or RGB image")

cmap = cm.get_cmap(colormap)
# Resize mask and apply colormap
overlay = mask.resize(img.size, resample=Resampling.BICUBIC)
overlay = (255 * cmap(np.asarray(overlay) ** 2)[:, :, :3]).astype(np.uint8)

overlay = (255 * cmap(np.asarray(overlay) ** 2)[:, :, 2 if len(img.getbands()) == 1 else slice(0, 3)]).astype(
Copy link
Owner

Choose a reason for hiding this comment

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

Final question: why taking the last channel, not first or second? Is any of those better for viz in grayscale? Or should we average accross the channel dimension?

np.uint8
)

# Overlay the image with the mask
return fromarray((alpha * np.asarray(img) + (1 - alpha) * cast(np.ndarray, overlay)).astype(np.uint8))
Loading