如何在Ruby中使用imagemagick(最好是mini_magic)查找“熵”?我需要这个作为更大项目的一部分,在图像中发现“有趣”,以便剪裁它。使用Ruby和imagemagick获取或计算图像的熵
我找到了一个好example in 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中获取直方图?
最重要的问题:这个算法是否有什么好处呢?你会建议一个更好的在图像的(部分)中找到“熵”或“变化像素数量”或“梯度深度”?
编辑:使用a.o.通过下面的答案提供的资源,我想出了工作代码:
# 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中使用,其允许智能切片和裁剪用于例如图像的图像。回形针。
非常感谢您使用。我的Matlab技能有点生疏,但我管理得很好,将它翻译成Ruby(并在FreeMat中重放)。 – berkes 2011-02-16 09:10:57