如何在 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 minimagick 中获取直方图?
最重要的问题:这个算法首先好吗?您是否会建议一种更好的方法来查找图像(部分)中的“熵”或“像素变化量”或“梯度深度”?
Edit:使用 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
.
这用于聪明作物宝石,它允许对图像进行智能切片和裁剪,例如回形针。