Class: ImageHash

Inherits:
Object
  • Object
show all
Defined in:
lib/image_hash.rb,
lib/image_hash/version.rb

Constant Summary collapse

VERSION =
'1.0.0'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ ImageHash

Returns a new instance of ImageHash.



5
6
7
# File 'lib/image_hash.rb', line 5

def initialize(path)
  @path = path
end

Class Method Details

.binary_distance(s1, s2) ⇒ Object



36
37
38
39
40
41
# 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) ⇒ Object



30
31
32
33
34
# 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) ⇒ Object



43
44
45
# 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) ⇒ Object



24
25
26
27
28
# 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

Instance Method Details

#binaryObject



17
18
19
20
21
# File 'lib/image_hash.rb', line 17

def binary
  scale_down
  desaturate
  pixels.map { |v| v > average_value ? 1 : 0 }
end

#binary_hashObject



9
10
11
# File 'lib/image_hash.rb', line 9

def binary_hash
  binary.join
end

#hashObject



13
14
15
# File 'lib/image_hash.rb', line 13

def hash
  self.class.binary_to_hex(binary_hash)
end