How to implement histogram equalization for images in tensorflow?

Question:

I’m a Deep Learning and Tensorflow novice.

I’m trying to modify cifar10 tensorflow tutorial for using it with faces input images.

How can I compute histogram equalization?

Is it possible to wrap solutions similar to the one in: Histogram equalization of grayscale images with NumPy ?

Asked By: ale-6

||

Answers:

For grayscale uint8 image you can use something like this:

def tf_equalize_histogram(image):
    values_range = tf.constant([0., 255.], dtype = tf.float32)
    histogram = tf.histogram_fixed_width(tf.to_float(image), values_range, 256)
    cdf = tf.cumsum(histogram)
    cdf_min = cdf[tf.reduce_min(tf.where(tf.greater(cdf, 0)))]

    img_shape = tf.shape(image)
    pix_cnt = img_shape[-3] * img_shape[-2]
    px_map = tf.round(tf.to_float(cdf - cdf_min) * 255. / tf.to_float(pix_cnt - 1))
    px_map = tf.cast(px_map, tf.uint8)

    eq_hist = tf.expand_dims(tf.gather_nd(px_map, tf.cast(image, tf.int32)), 2)
    return eq_hist

For test:

import tensorflow as tf
import numpy as np
import cv2

image_ph = tf.placeholder(tf.uint8, shape = [None, None, 1])
image_eq_hist = tf_equalize_histogram(image_ph)

image = cv2.imread("./test_gs.png", 0)
image = np.reshape(image, (image.shape[0], image.shape[1], 1))
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    image_eq_hist_ = sess.run(image_eq_hist, feed_dict = {image_ph : image})

cv2.imshow("eq_cv", cv2.equalizeHist(image))
cv2.imshow("eq", image_eq_hist_)
cv2.waitKey()
Answered By: Vladimir Bystricky

A slight modification for the previous answer

def tf_equalize(image):
    values_range = tf.constant([0., 255.], dtype = tf.float32)
    histogram = tf.histogram_fixed_width(image, values_range, 256)
    histogram = tf.cast(histogram,tf.float32)
    cdf = cdf/tf.reduce_sum(cdf)
    px_map = 255.0*(cdf / tf.reduce_max(cdf))
    px_map = tf.cast(px_map, tf.uint8)

    eq_hist = tf.expand_dims(tf.gather_nd(px_map, tf.cast(image, tf.int32)), 2)
    return eq_hist
Answered By: Nehad Hirmiz