Skip to content

Instantly share code, notes, and snippets.

@acrookston
Last active December 26, 2015 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acrookston/7209460 to your computer and use it in GitHub Desktop.
Save acrookston/7209460 to your computer and use it in GitHub Desktop.
Cross-posting from https://forrst.com/posts/Collecting_colours_from_an_image_Ruby-Lgo Collecting colours from an image with Ruby
require 'rmagick'
number_of_colors = 100
file_path = "/path/to/file.jpg"
begin
temp_file = Magick::Image.read(file_path).first.quantize(number_of_colors)
pixels = {}
pixel_count = 0
temp_file.each_pixel do |p,c,r|
pixel_count += 1
pix = p.to_color(Magick::AllCompliance, false, 8)
pixels[pix] = (pixels[pix] || 0) + 1
end
puts "Pixels: #{pixel_count}"
pixels.sort { |a,b| b[1] <=> a[1] }
rescue Magick::ImageMagickError
{}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment