2015-12-07 83 views
5

有没有简单的方法来计算图像的颜色直方图?也许通过滥用内部代码tf.histogram_summary?从我所看到的,这个代码不是很模块化,直接调用一些C++代码。使用张量流创建图像的颜色直方图

在此先感谢。

+0

你想使用在以后的TF计算直方图,或输出的直方图最终目标? – dga

+0

@dga我在后面的TF计算中使用它。 – panmari

回答

5

我会用tf.unsorted_segment_sum,其中“段ID”从颜色值计算和事情,你和为tf.ones载体。请注意,tf.unsorted_segment_sum可能更好地被认为是“桶和”。它实现dest[segment] += thing_to_sum - 完全是直方图所需的操作。

在略微伪代码(意思是我没有运行此):

binned_values = tf.reshape(tf.floor(img_r * (NUM_BINS-1)), [-1]) 
binned_values = tf.cast(binned_values, tf.int32) 
ones = tf.ones_like(binned_values, dtype=tf.int32) 
counts = tf.unsorted_segment_sum(ones, binned_values, NUM_BINS) 

能在一通,如果你想做到这一点,而不是分离出R,G,B值与分裂巧妙地构建你的“人”看起来像红色的“100100”,绿色的“010010”等,但我怀疑它会整体变慢,而且难以阅读。我只是做你上面提出的拆分。

2

这是我现在使用什么:

# Assumption: img is a tensor of the size [img_width, img_height, 3], normalized to the range [-1, 1]. 
with tf.variable_scope('color_hist_producer') as scope: 
    bin_size = 0.2 
    hist_entries = [] 
    # Split image into single channels 
    img_r, img_g, img_b = tf.split(2, 3, img) 
    for img_chan in [img_r, img_g, img_b]: 
    for idx, i in enumerate(np.arange(-1, 1, bin_size)): 
     gt = tf.greater(img_chan, i) 
     leq = tf.less_equal(img_chan, i + bin_size) 
     # Put together with logical_and, cast to float and sum up entries -> gives count for current bin. 
     hist_entries.append(tf.reduce_sum(tf.cast(tf.logical_and(gt, leq), tf.float32))) 

    # Pack scalars together to a tensor, then normalize histogram. 
    hist = tf.nn.l2_normalize(tf.pack(hist_entries), 0)