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

Vectorize Equalization #201

Merged
merged 8 commits into from
Apr 5, 2022
Merged
Changes from 4 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
31 changes: 19 additions & 12 deletions keras_cv/layers/preprocessing/equalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,15 @@ def equalize_channel(self, image, channel_index):
histogram = tf.histogram_fixed_width(image, [0, 255], nbins=self.bins)

# For the purposes of computing the step, filter out the nonzeros.
nonzero = tf.where(tf.not_equal(histogram, 0))
nonzero_histogram = tf.reshape(tf.gather(histogram, nonzero), [-1])
step = (tf.reduce_sum(nonzero_histogram) - nonzero_histogram[-1]) // (
# Zeroes are replaced by 1410065408 while calculating min to keep shape
quantumalaviya marked this conversation as resolved.
Show resolved Hide resolved
# constant across input sizes for compatibility with vectorized_map
histogram_without_zeroes = tf.where(
tf.equal(histogram, 0),
tf.multiply(tf.ones((), tf.int32), 1410065408),
quantumalaviya marked this conversation as resolved.
Show resolved Hide resolved
quantumalaviya marked this conversation as resolved.
Show resolved Hide resolved
histogram,
)

step = (tf.reduce_sum(histogram) - tf.reduce_min(histogram_without_zeroes)) // (
quantumalaviya marked this conversation as resolved.
Show resolved Hide resolved
self.bins - 1
)

Expand All @@ -81,22 +87,23 @@ def build_mapping(histogram, step):
result = tf.cond(
tf.equal(step, 0),
lambda: image,
lambda: tf.cast(
tf.gather(build_mapping(histogram, step), tf.cast(image, tf.int32)),
self.compute_dtype,
),
lambda: tf.gather(build_mapping(histogram, step), image),
)

return result

def augment_image(self, image, transformation=None):
dtype = image.dtype
quantumalaviya marked this conversation as resolved.
Show resolved Hide resolved
image = tf.cast(image, tf.int32)
image = preprocessing.transform_value_range(image, self.value_range, (0, 255))
r = self.equalize_channel(image, 0)
g = self.equalize_channel(image, 1)
b = self.equalize_channel(image, 2)
image = tf.stack([r, g, b], axis=-1)
image = tf.vectorized_map(
lambda channel: self.equalize_channel(image, channel),
tf.range(tf.shape(image)[-1]),
)

image = tf.transpose(image, [1, 2, 0])
image = preprocessing.transform_value_range(image, (0, 255), self.value_range)
return image
return tf.cast(image, dtype)

def get_config(self):
config = super().get_config()
Expand Down