Class: Colorscore::Histogram

Inherits:
Object
  • Object
show all
Defined in:
lib/colorscore/histogram.rb

Instance Method Summary collapse

Constructor Details

#initialize(image_path, options = {}) ⇒ Histogram

Returns a new instance of Histogram.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/colorscore/histogram.rb', line 5

def initialize(image_path, options = {})
  params = [
    '-resize 400x400',
    '-format %c',
    "-dither #{options.fetch(:dither) { 'None' }}",
    "-quantize #{options.fetch(:quantize) { 'YIQ' }}",
    "-colors #{options.fetch(:colors) { 16 }.to_i}",
    "-depth #{options.fetch(:depth) { 8 }.to_i}",
    '-alpha deactivate '
  ]

  #params.unshift(options[:resize]) if options[:resize]

  output = `convert #{image_path.shellescape} #{ params.join(' ') } histogram:info:-`
  @lines = output.lines.map(&:strip).reject(&:empty?).
    sort_by { |l| l[/(\d+):/, 1].to_i }
end

Instance Method Details

#color_countsObject



29
30
31
# File 'lib/colorscore/histogram.rb', line 29

def color_counts
  @lines.map { |line| line.split(':')[0].to_i }
end

#colorsObject

Returns an array of colors in descending order of occurances.



24
25
26
27
# File 'lib/colorscore/histogram.rb', line 24

def colors
  hex_values = @lines.map { |line| line[/#([0-9A-F]{6})/, 1] }.compact
  hex_values.map { |hex| Color::RGB.from_html(hex) }
end

#scoresObject



33
34
35
36
37
# File 'lib/colorscore/histogram.rb', line 33

def scores
  total = color_counts.inject(:+).to_f
  scores = color_counts.map { |count| count / total }
  scores.zip(colors)
end