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

Visualize images from the batch #2063

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
21 changes: 17 additions & 4 deletions src/anomalib/utils/visualization/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
from skimage.segmentation import mark_boundaries

from anomalib import TaskType
from anomalib.data.utils import read_image
from anomalib.utils.post_processing import add_anomalous_label, add_normal_label, draw_boxes, superimpose_anomaly_map

from .base import BaseVisualizer, GeneratorResult, VisualizationStep
Expand Down Expand Up @@ -127,6 +126,21 @@ def generate(self, **kwargs) -> Iterator[GeneratorResult]:
raise ValueError(msg)
return self._visualize_batch(outputs)

def denormalize_imagenet_to_uint8(self, image_normalized: np.ndarray) -> np.ndarray:
"""Convert the NumPy array image from the ImageNet-normalized scale to uint8 [0, 255].

Args:
image_normalized (np.ndarray): A NumPy array of image(s) that are normalized with ImageNet statistics.

Returns:
np.ndarray: Image(s) in the uint8 format.
"""
std = np.array([0.229, 0.224, 0.225]) * 255
mean = np.array([0.485, 0.456, 0.406]) * 255

# We do not clip pixel values here, in case of hiding the problematic input.
return (image_normalized * std + mean).astype(np.uint8)

def _visualize_batch(self, batch: dict) -> Iterator[GeneratorResult]:
"""Yield a visualization result for each item in the batch.

Expand All @@ -139,9 +153,8 @@ def _visualize_batch(self, batch: dict) -> Iterator[GeneratorResult]:
batch_size = batch["image"].shape[0]
for i in range(batch_size):
if "image_path" in batch:
height, width = batch["image"].shape[-2:]
image = (read_image(path=batch["image_path"][i]) * 255).astype(np.uint8)
image = cv2.resize(image, dsize=(width, height), interpolation=cv2.INTER_AREA)
image = batch["image"][i].cpu().numpy().transpose(1, 2, 0) # HWC, RGB
Copy link
Collaborator

Choose a reason for hiding this comment

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

I am not sure if this is the best approach. I would recommend creating a new visualizer sub-classed from

class BaseVisualizer(ABC):
. You can access the batch in a similar manner as
outputs = kwargs.get("outputs", None)
. This new class can then safely make the strong assumption that the images are always normalized to imagenet scales. Additionally, it will not break the functionality to load images from the file-path.
We are planning on refactoring the visualization callback so that we can pass the visualizers to the engine rather than hard-coding it but for now you can add the new visualizer to the list here
visualizers=ImageVisualizer(task=self.task, normalize=self.normalization == NormalizationMethod.NONE),

Another option is to invert the normalization transforms attached to the model

Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
or from the dataloader. But it might require a more complex solution.

image = self.denormalize_imagenet_to_uint8(image)
elif "video_path" in batch:
height, width = batch["image"].shape[-2:]
image = batch["original_image"][i].squeeze().cpu().numpy()
Expand Down