-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathblockhash.py
More file actions
executable file
·209 lines (165 loc) · 7.16 KB
/
blockhash.py
File metadata and controls
executable file
·209 lines (165 loc) · 7.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#! /usr/bin/env python
#
# Perceptual image hash calculation tool based on algorithm descibed in
# Block Mean Value Based Image Perceptual Hashing by Bian Yang, Fan Gu and Xiamu Niu
#
# Copyright 2014 Commons Machinery http://commonsmachinery.se/
# Distributed under an MIT license, please see LICENSE in the top dir.
import math
import argparse
import PIL.Image as Image
def median(data):
data = sorted(data)
length = len(data)
if length % 2 == 0:
return (data[length // 2 - 1] + data[length // 2]) / 2.0
return data[length // 2]
def total_value_rgba(im, data, x, y):
r, g, b, a = data[y * im.size[0] + x]
if a == 0:
return 765
else:
return r + g + b
def total_value_rgb(im, data, x, y):
r, g, b = data[y * im.size[0] + x]
return r + g + b
def translate_blocks_to_bits(blocks, pixels_per_block):
half_block_value = pixels_per_block * 256 * 3 / 2
# Compare medians across four horizontal bands
bandsize = len(blocks) // 4
for i in range(4):
m = median(blocks[i * bandsize : (i + 1) * bandsize])
for j in range(i * bandsize, (i + 1) * bandsize):
v = blocks[j]
# Output a 1 if the block is brighter than the median.
# With images dominated by black or white, the median may
# end up being 0 or the max value, and thus having a lot
# of blocks of value equal to the median. To avoid
# generating hashes of all zeros or ones, in that case output
# 0 if the median is in the lower value space, 1 otherwise
blocks[j] = int(v > m or (abs(v - m) < 1 and m > half_block_value))
def bits_to_hexhash(bits):
return '{0:0={width}x}'.format(int(''.join([str(x) for x in bits]), 2), width = len(bits) // 4)
def blockhash_even(im, bits):
if im.mode == 'RGBA':
total_value = total_value_rgba
elif im.mode == 'RGB':
total_value = total_value_rgb
else:
raise RuntimeError('Unsupported image mode: {}'.format(im.mode))
data = im.getdata()
width, height = im.size
blocksize_x = width // bits
blocksize_y = height // bits
result = []
for y in range(bits):
for x in range(bits):
value = 0
for iy in range(blocksize_y):
for ix in range(blocksize_x):
cx = x * blocksize_x + ix
cy = y * blocksize_y + iy
value += total_value(im, data, cx, cy)
result.append(value)
translate_blocks_to_bits(result, blocksize_x * blocksize_y)
return bits_to_hexhash(result)
def blockhash(im, bits):
if im.mode == 'RGBA':
total_value = total_value_rgba
elif im.mode == 'RGB':
total_value = total_value_rgb
else:
raise RuntimeError('Unsupported image mode: {}'.format(im.mode))
data = im.getdata()
width, height = im.size
even_x = width % bits == 0
even_y = height % bits == 0
if even_x and even_y:
return blockhash_even(im, bits)
blocks = [[0 for col in range(bits)] for row in range(bits)]
block_width = float(width) / bits
block_height = float(height) / bits
for y in range(height):
if even_y:
# don't bother dividing y, if the size evenly divides by bits
block_top = block_bottom = int(y // block_height)
weight_top, weight_bottom = 1, 0
else:
y_frac, y_int = math.modf((y + 1) % block_height)
weight_top = (1 - y_frac)
weight_bottom = (y_frac)
# y_int will be 0 on bottom/right borders and on block boundaries
if y_int > 0 or (y + 1) == height:
block_top = block_bottom = int(y // block_height)
else:
block_top = int(y // block_height)
block_bottom = int(-(-y // block_height)) # int(math.ceil(float(y) / block_height))
for x in range(width):
value = total_value(im, data, x, y)
if even_x:
# don't bother dividing x, if the size evenly divides by bits
block_left = block_right = int(x // block_width)
weight_left, weight_right = 1, 0
else:
x_frac, x_int = math.modf((x + 1) % block_width)
weight_left = (1 - x_frac)
weight_right = (x_frac)
# x_int will be 0 on bottom/right borders and on block boundaries
if x_int > 0 or (x + 1) == width:
block_left = block_right = int(x // block_width)
else:
block_left = int(x // block_width)
block_right = int(-(-x // block_width)) # int(math.ceil(float(x) / block_width))
# add weighted pixel value to relevant blocks
blocks[block_top][block_left] += value * weight_top * weight_left
blocks[block_top][block_right] += value * weight_top * weight_right
blocks[block_bottom][block_left] += value * weight_bottom * weight_left
blocks[block_bottom][block_right] += value * weight_bottom * weight_right
result = [blocks[row][col] for row in range(bits) for col in range(bits)]
translate_blocks_to_bits(result, block_width * block_height)
return bits_to_hexhash(result)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--quick', type=bool, default=False,
help='Use quick hashing method. Default: False')
parser.add_argument('--bits', type=int, default=16,
help='Create hash of size N^2 bits. Default: 16')
parser.add_argument('--size',
help='Resize image to specified size before hashing, e.g. 256x256')
parser.add_argument('--interpolation', type=int, default=1, choices=[1, 2, 3, 4],
help='Interpolation method: 1 - nearest neightbor, 2 - bilinear, 3 - bicubic, 4 - antialias. Default: 1')
parser.add_argument('--debug', action='store_true',
help='Print hashes as 2D maps (for debugging)')
parser.add_argument('filenames', nargs='+')
args = parser.parse_args()
if args.interpolation == 1:
interpolation = Image.NEAREST
elif args.interpolation == 2:
interpolation = Image.BILINEAR
elif args.interpolation == 3:
interpolation = Image.BICUBIC
elif args.interpolation == 4:
interpolation = Image.ANTIALIAS
if args.quick:
method = blockhash_even
else:
method = blockhash
for fn in args.filenames:
im = Image.open(fn)
# convert indexed/grayscale images to RGB
if im.mode == '1' or im.mode == 'L' or im.mode == 'P':
im = im.convert('RGB')
elif im.mode == 'LA':
im = im.convert('RGBA')
if args.size:
size = args.size.split('x')
size = (int(size[0]), int(size[1]))
im = im.resize(size, interpolation)
hash = method(im, args.bits)
print('{hash} {fn}'.format(fn=fn, hash=hash))
if args.debug:
bin_hash = '{:0{width}b}'.format(int(hash, 16), width=args.bits ** 2)
map = [bin_hash[i:i+args.bits] for i in range(0, len(bin_hash), args.bits)]
print("")
print("\n".join(map))
print("")