使用Ruby和imagemagick获取或计算图像的熵 [英] Get, or calculate the entropy of an image with Ruby and imagemagick

查看:258
本文介绍了使用Ruby和imagemagick获取或计算图像的熵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Ruby中找到imagemagick的entropy,最好是mini_magic?我需要这个作为更大项目的一部分,在图像中找到兴趣,以便裁剪

How to find the "entropy" with imagemagick, preferably mini_magic, in Ruby? I need this as part of a larger project, finding "interestingness" in an image so to crop it.

我找到了一个好的 Python / Django中的示例,它提供以下伪代码:

I found a good example in Python/Django, which gives the following pseudo-code:

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中获取直方图?

My questions: Did I interprete the Django/Python code correct? How can I fetch a histogram in ruby's mini_magick if at all?

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

Most important question: is this algorithm any good in the first place? Would you suggest a better one to find the "entropy" or "amount of changing pixels" or "gradient depth" in (parts of) images?

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

Edit: Using a.o. the resources provided by the answer below, I came up with the working code:

# 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 ::图片

Where image_data is an RMagick::Image.

这用于 smartcropper gem ,它允许用例如智能切片和裁剪图像回形针。

This is used in the smartcropper gem, which allows smart slicing and cropping for images with e.g. paperclip.

推荐答案

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

Entropy is explained here (with MATLAB source, but hopefully the qualitative explanation helps):

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

有关更正式的解释,请参阅:

For a more formal explanation, see:

信息理论要素(第2章),封面和托马斯

这篇关于使用Ruby和imagemagick获取或计算图像的熵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆