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

Fix Perturbate on RGB images #306

Merged
merged 2 commits into from
Jan 31, 2023
Merged

Conversation

adrhill
Copy link
Collaborator

@adrhill adrhill commented Jan 31, 2023

Closes #299.

Perturbation functions are now applied separately to each color-channel.

perturbation_function Image
"mean" peppers_mean
"zeros" peppers_zeros
"gaussian" peppers_gaussian

These images were created using perturbate_on_batch:

import numpy as np
from PIL import Image
import tensorflow as tf

tf.compat.v1.disable_eager_execution()

from innvestigate.tools.perturbate import Perturbation

im = Image.open("peppers.tiff")
im = im.resize((224, 224), resample=0)

# Convert image to array
assert tf.keras.backend.image_data_format() == "channels_last"


def im2array(im):
    """Covert image to array in channels_last format."""
    x = np.array(im) / 255
    # x = np.moveaxis(x, 2, 0)  # for channels_first
    return np.reshape(x, (1, *(x.shape)))  # add batch dim


def array2im(a):
    """Convert array in channels_last format to image."""
    a = np.uint8(a[0, :, :, :] * 255)
    # a = np.moveaxis(a, 0, 2)  # for channels_first
    return Image.fromarray(a)


x = im2array(im)

# Random analysis:
a = np.random.rand(*x.shape)

# Create innvestigate's Perturbation
num_perturbed_regions = 8
perturbation_function = "mean"
region_shape = (32, 32)

p = Perturbation(
    perturbation_function,
    num_perturbed_regions=num_perturbed_regions,
    region_shape=region_shape,
    value_range=(0, 1),
)

# Perturb and show image
x_perturbated = p.perturbate_on_batch(x, a)
im_perturbated = array2im(x_perturbated)
im_perturbated.save(f"peppers_{perturbation_function}.png")

@adrhill adrhill merged commit e2b6332 into albermax:master Jan 31, 2023
@adrhill adrhill deleted the ah/fix_perturbate branch January 31, 2023 15:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[BUG] Perturbation.perturbate_regions for RGB images
1 participant