class ImageHash

Constants

VERSION

Public Class Methods

binary_distance(s1, s2) click to toggle source
# File lib/image_hash.rb, line 36
def binary_distance(s1, s2)
  diffs = s1.each_char.zip(s2.each_char).map do |c1, c2|
    c1 == c2 ? 0 : 1
  end
  diffs.inject(&:+)
end
binary_to_hex(binary) click to toggle source
# File lib/image_hash.rb, line 30
def binary_to_hex(binary)
  bits = binary.each_char.map(&:to_i).each_slice(8)
  hex_values = bits.map { |s| s.join.to_i(2).to_s(16).rjust(2, '0') }
  hex_values.join
end
distance(s1, s2) click to toggle source
# File lib/image_hash.rb, line 43
def distance(s1, s2)
  binary_distance(hex_to_binary(s1), hex_to_binary(s2))
end
hex_to_binary(hex) click to toggle source
# File lib/image_hash.rb, line 24
def hex_to_binary(hex)
  nums = hex.each_char.each_slice(2)
  bin_values = nums.map { |s| s.join.to_i(16).to_s(2).rjust(8, '0') }
  bin_values.join
end
new(path) click to toggle source
# File lib/image_hash.rb, line 5
def initialize(path)
  @path = path
end

Public Instance Methods

binary() click to toggle source
# File lib/image_hash.rb, line 17
def binary
  scale_down
  desaturate
  pixels.map { |v| v > average_value ? 1 : 0 }
end
binary_hash() click to toggle source
# File lib/image_hash.rb, line 9
def binary_hash
  binary.join
end
hash() click to toggle source
# File lib/image_hash.rb, line 13
def hash
  self.class.binary_to_hex(binary_hash)
end

Private Instance Methods

average_value() click to toggle source
# File lib/image_hash.rb, line 68
def average_value
  @average_value ||= pixels.inject(&:+) / pixels.size
end
desaturate() click to toggle source
# File lib/image_hash.rb, line 54
def desaturate
  image.format('jpg', 0, colorspace: 'Gray')
end
image() click to toggle source
# File lib/image_hash.rb, line 58
def image
  @image ||= MiniMagick::Image.open(@path)
end
pixels() click to toggle source
# File lib/image_hash.rb, line 62
def pixels
  @pixels ||= image.get_pixels.flat_map do |row|
    row.map { |r, g, b| rgb_to_value(r, g, b) }
  end
end
rgb_to_value(r, g, b) click to toggle source
# File lib/image_hash.rb, line 72
def rgb_to_value(r, g, b)
  r /= 255.0
  g /= 255.0
  b /= 255.0
  max = [r, g, b].max
  min = [r, g, b].min
  (max + min) / 2.0
end
scale_down() click to toggle source
# File lib/image_hash.rb, line 50
def scale_down
  image.resize('8x8!')
end