如何在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