Debian Codegraph @

blurhash/blurhash.py

raw symbols SCIP
1 """
2 Pure python blurhash decoder with no additional dependencies, for
3 both de- and encoding.
4
5 Very close port of the original Swift implementation by Dag Ă…gren.
6 """
7
8 import math
9
10 # Alphabet for base 83
11 alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~"
12 alphabet_values = dict(zip(alphabet, range(len(alphabet))))
13
14 def base83_decode(base83_str):
15 """
16 Decodes a base83 string, as used in blurhash, to an integer.
17 """
18 value = 0
19 for base83_char in base83_str:
20 value = value * 83 + alphabet_values[base83_char]
21 return value
22
23 def base83_encode(value, length):
24 """
25 Decodes an integer to a base83 string, as used in blurhash.
26
27 Length is how long the resulting string should be. Will complain
28 if the specified length is too short.
29 """
30 if int(value) // (83 ** (length)) != 0:
31 raise ValueError("Specified length is too short to encode given value.")
32
33 result = ""
34 for i in range(1, length + 1):
35 digit = int(value) // (83 ** (length - i)) % 83
36 result += alphabet[int(digit)]
37 return result
38
39 def srgb_to_linear(value):
40 """
41 srgb 0-255 integer to linear 0.0-1.0 floating point conversion.
42 """
43 value = float(value) / 255.0
44 if value <= 0.04045:
45 return value / 12.92
46 return math.pow((value + 0.055) / 1.055, 2.4)
47
48 def sign_pow(value, exp):
49 """
50 Sign-preserving exponentiation.
51 """
52 return math.copysign(math.pow(abs(value), exp), value)
53
54 def linear_to_srgb(value):
55 """
56 linear 0.0-1.0 floating point to srgb 0-255 integer conversion.
57 """
58 value = max(0.0, min(1.0, value))
59 if value <= 0.0031308:
60 return int(value * 12.92 * 255 + 0.5)
61 return int((1.055 * math.pow(value, 1 / 2.4) - 0.055) * 255 + 0.5)
62
63 def blurhash_components(blurhash):
64 """
65 Decodes and returns the number of x and y components in the given blurhash.
66 """
67 if len(blurhash) < 6:
68 raise ValueError("BlurHash must be at least 6 characters long.")
69
70 # Decode metadata
71 size_info = base83_decode(blurhash[0])
72 size_y = int(size_info / 9) + 1
73 size_x = (size_info % 9) + 1
74
75 return size_x, size_y
76
77 def blurhash_decode(blurhash, width, height, punch = 1.0, linear = False):
78 """
79 Decodes the given blurhash to an image of the specified size.
80
81 Returns the resulting image a list of lists of 3-value sRGB 8 bit integer
82 lists. Set linear to True if you would prefer to get linear floating point
83 RGB back.
84
85 The punch parameter can be used to de- or increase the contrast of the
86 resulting image.
87
88 As per the original implementation it is suggested to only decode
89 to a relatively small size and then scale the result up, as it
90 basically looks the same anyways.
91 """
92 if len(blurhash) < 6:
93 raise ValueError("BlurHash must be at least 6 characters long.")
94
95 # Decode metadata
96 size_info = base83_decode(blurhash[0])
97 size_y = int(size_info / 9) + 1
98 size_x = (size_info % 9) + 1
99
100 quant_max_value = base83_decode(blurhash[1])
101 real_max_value = (float(quant_max_value + 1) / 166.0) * punch
102
103 # Make sure we at least have the right number of characters
104 if len(blurhash) != 4 + 2 * size_x * size_y:
105 raise ValueError("Invalid BlurHash length.")
106
107 # Decode DC component
108 dc_value = base83_decode(blurhash[2:6])
109 colours = [(
110 srgb_to_linear(dc_value >> 16),
111 srgb_to_linear((dc_value >> 8) & 255),
112 srgb_to_linear(dc_value & 255)
113 )]
114
115 # Decode AC components
116 for component in range(1, size_x * size_y):
117 ac_value = base83_decode(blurhash[4+component*2:4+(component+1)*2])
118 colours.append((
119 sign_pow((float(int(ac_value / (19 * 19))) - 9.0) / 9.0, 2.0) * real_max_value,
120 sign_pow((float(int(ac_value / 19) % 19) - 9.0) / 9.0, 2.0) * real_max_value,
121 sign_pow((float(ac_value % 19) - 9.0) / 9.0, 2.0) * real_max_value
122 ))
123
124 # Return image RGB values, as a list of lists of lists,
125 # consumable by something like numpy or PIL.
126 pixels = []
127 for y in range(height):
128 pixel_row = []
129 for x in range(width):
130 pixel = [0.0, 0.0, 0.0]
131
132 for j in range(size_y):
133 for i in range(size_x):
134 basis = math.cos(math.pi * float(x) * float(i) / float(width)) * \
135 math.cos(math.pi * float(y) * float(j) / float(height))
136 colour = colours[i + j * size_x]
137 pixel[0] += colour[0] * basis
138 pixel[1] += colour[1] * basis
139 pixel[2] += colour[2] * basis
140 if linear == False:
141 pixel_row.append([
142 linear_to_srgb(pixel[0]),
143 linear_to_srgb(pixel[1]),
144 linear_to_srgb(pixel[2]),
145 ])
146 else:
147 pixel_row.append(pixel)
148 pixels.append(pixel_row)
149 return pixels
150
151 def blurhash_encode(image, components_x = 4, components_y = 4, linear = False):
152 """
153 Calculates the blurhash for an image using the given x and y component counts.
154
155 Image should be a 3-dimensional array, with the first dimension being y, the second
156 being x, and the third being the three rgb components that are assumed to be 0-255
157 srgb integers (incidentally, this is the format you will get from a PIL RGB image).
158
159 You can also pass in already linear data - to do this, set linear to True. This is
160 useful if you want to encode a version of your image resized to a smaller size (which
161 you should ideally do in linear colour).
162 """
163 if components_x < 1 or components_x > 9 or components_y < 1 or components_y > 9:
164 raise ValueError("x and y component counts must be between 1 and 9 inclusive.")
165 height = float(len(image))
166 width = float(len(image[0]))
167
168 # Convert to linear if neeeded
169 image_linear = []
170 if linear == False:
171 for y in range(int(height)):
172 image_linear_line = []
173 for x in range(int(width)):
174 image_linear_line.append([
175 srgb_to_linear(image[y][x][0]),
176 srgb_to_linear(image[y][x][1]),
177 srgb_to_linear(image[y][x][2])
178 ])
179 image_linear.append(image_linear_line)
180 else:
181 image_linear = image
182
183 # Calculate components
184 components = []
185 max_ac_component = 0.0
186 for j in range(components_y):
187 for i in range(components_x):
188 norm_factor = 1.0 if (i == 0 and j == 0) else 2.0
189 component = [0.0, 0.0, 0.0]
190 for y in range(int(height)):
191 for x in range(int(width)):
192 basis = norm_factor * math.cos(math.pi * float(i) * float(x) / width) * \
193 math.cos(math.pi * float(j) * float(y) / height)
194 component[0] += basis * image_linear[y][x][0]
195 component[1] += basis * image_linear[y][x][1]
196 component[2] += basis * image_linear[y][x][2]
197
198 component[0] /= (width * height)
199 component[1] /= (width * height)
200 component[2] /= (width * height)
201 components.append(component)
202
203 if not (i == 0 and j == 0):
204 max_ac_component = max(max_ac_component, abs(component[0]), abs(component[1]), abs(component[2]))
205
206 # Encode components
207 dc_value = (linear_to_srgb(components[0][0]) << 16) + \
208 (linear_to_srgb(components[0][1]) << 8) + \
209 linear_to_srgb(components[0][2])
210
211 quant_max_ac_component = int(max(0, min(82, math.floor(max_ac_component * 166 - 0.5))))
212 ac_component_norm_factor = float(quant_max_ac_component + 1) / 166.0
213
214 ac_values = []
215 for r, g, b in components[1:]:
216 ac_values.append(
217 int(max(0.0, min(18.0, math.floor(sign_pow(r / ac_component_norm_factor, 0.5) * 9.0 + 9.5)))) * 19 * 19 + \
218 int(max(0.0, min(18.0, math.floor(sign_pow(g / ac_component_norm_factor, 0.5) * 9.0 + 9.5)))) * 19 + \
219 int(max(0.0, min(18.0, math.floor(sign_pow(b / ac_component_norm_factor, 0.5) * 9.0 + 9.5))))
220 )
221
222 # Build final blurhash
223 blurhash = ""
224 blurhash += base83_encode((components_x - 1) + (components_y - 1) * 9, 1)
225 blurhash += base83_encode(quant_max_ac_component, 1)
226 blurhash += base83_encode(dc_value, 4)
227 for ac_value in ac_values:
228 blurhash += base83_encode(ac_value, 2)
229
230 return blurhash