5

如何在 Ruby 中使用 imagemagick(最好是 mini_magic)找到“熵”?我需要这个作为一个更大项目的一部分,在图像中找到“有趣”以便裁剪它

我在 Python/Django 中找到了一个很好的例子,它给出了以下伪代码:

image = Image.open('example.png')
histogram = image.histogram() # Fetch a list of pixel counts, one for each pixel value in the source image

#Normalize, or average the result.
for each histogram as pixel
  histogram_recalc << pixel / histogram.size
endfor

#Place the pixels on a logarithmic scale, to enhance the result.
for each histogram_recalc as pixel
  if pixel != 0
    entropy_list << log2(pixel)
  endif
endfor

#Calculate the total of the enhanced pixel-values and invert(?) that.
entropy = entroy_list.sum * -1

这将转化为公式entropy = -sum(p.*log2(p))

我的问题:我对 Django/Python 代码的解释是否正确?如果有的话,我如何在 ruby​​ 的 mini_magick 中获取直方图?

最重要的问题:首先,这个算法有什么好处吗?你会建议一个更好的方法来找到图像(部分)中的“熵”或“变化像素的数量”或“梯度深度”吗?

编辑:使用下面答案提供的资源,我想出了工作代码:

# Compute the entropy of an image slice.
def entropy_slice(image_data, x, y, width, height)
  slice = image_data.crop(x, y, width, height)
  entropy = entropy(slice)
end

# Compute the entropy of an image, defined as -sum(p.*log2(p)).
# Note: instead of log2, only available in ruby > 1.9, we use
# log(p)/log(2). which has the same effect.
def entropy(image_slice)
  hist = image_slice.color_histogram
  hist_size = hist.values.inject{|sum,x| sum ? sum + x : x }.to_f

  entropy = 0
  hist.values.each do |h|
    p = h.to_f / hist_size
    entropy += (p * (Math.log(p)/Math.log(2))) if p != 0
  end
  return entropy * -1
end

其中 image_data 是一个RMagick::Image.

这在smartcropper gem中使用,它允许使用例如回形针对图像进行智能切片和裁剪。

4

2 回答 2

1

这里解释了熵(使用 MATLAB 源代码,但希望定性解释会有所帮助):

熵简介(MATLAB 中的数据挖掘)

更正式的解释见:

“信息论的要素”(第 2 章),作者 Cover 和 Thomas

于 2011-02-16T08:36:47.807 回答
0

方面的Array#entropy

require 'facets'
puts File.read('path/to/image.png').chars.entropy
于 2016-10-29T00:05:36.000 回答