2

Is it possible to fetch the histogram of an image with mini_magick or image_science?

I am afraid mini_magicks usage of mogrify does not allow such information retrieval. image_science is hardly documented and seems to be limited to thumbnail scaling and cropping only.

One route to take, would be to iterate over each pixel and extract its values, in Ruby. But that requires information on pixels, which I cannot get to in mini_magick either.

I can fallback to either RMagick or im_magick, but those are either less popular/unknown or reportedly bad in performance.

For the record: this is a part of an earlier question about finding the entropy of parts of images.

3 Answers 3

7

A workaround is to use mini_magick to convert the file to PNG format, store the result in a temporary file, and then use the "almost-pure Ruby" png library or the actually-pure Ruby chunky_png to go over the result. Both libraries make it easy to iterate over the image pixel by pixel.

I'm suspecting you specified mini_magick/image_science because these are a lot easier to install than, say, rmagick. The reason this workaround might work for you, then, is that png and chunky_png are pain-free installs due to a lack of dependencies.

The only thing you'd be giving up is a little performance but if it's a real problem, oily_png can extend chunky_png with some extra C magic.. so there'll be a compile, but it shouldn't be a painful one.

OK, I've come up with some code for this that works:

require 'mini_magick'
require 'chunky_png'

i = MiniMagick::Image.open("a.jpg")

i.format('png')

p = ChunkyPNG::Image.from_io(StringIO.new(i.to_blob))

p.height.times do |y|
  p.width.times do |x|
    p[x, y]  # => here's your pixel..
  end
end

You can take the histogram creation part from there ;-)

Also, I just noticed that ImageMagick itself can create histograms from the command line. This might not help if you want something specific but I thought I'd throw it out there.

1
5

You can get image in histogram format from ImageMagick by this command:

convert penguinsonice.bmp -format %c histogram:info:

and code for gem 'mini_magick' that wrap ImageMagick for Ruby:

require "mini_magick"

module MiniMagick
 class Image
  def get_dominant_color
   color = run_command("convert", path, "-format", "%c\n",  "-colors", 1, "-depth", 8, "histogram:info:").split(' ');
   # color = "   1764000: (208,195,161) #D0C3A1 srgb(208,195,161)\n\n"
   {
     hex: color[2], 
     rgb: color[1][1..-2].split(',')
   }
  end
 end
end


i = MiniMagick::Image.open("/home/a.jpg")

p i.get_dominant_color()[:hex]
p i.get_dominant_color()[:rgb]
0

Mini-magick is a very thin layer over the imagemagick binary. If it doesn't support one of Imagemagick's options, it's easy to add.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.