blurhash.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. """
  2. Copyright (c) 2019 Lorenz Diener
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. * The above copyright notice and this permission notice shall be included
  10. in all copies or substantial portions of the Software.
  11. * You and any organization you work for may not promote white supremacy, hate
  12. speech and homo- or transphobia - this license is void if you do.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. SOFTWARE.
  20. https://github.com/halcy/blurhash-python
  21. Pure python blurhash decoder with no additional dependencies, for
  22. both de- and encoding.
  23. Very close port of the original Swift implementation by Dag Ågren.
  24. """
  25. import math
  26. # Alphabet for base 83
  27. alphabet = \
  28. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" + \
  29. "abcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~"
  30. alphabet_values = dict(zip(alphabet, range(len(alphabet))))
  31. def base83_decode(base83_str):
  32. """
  33. Decodes a base83 string, as used in blurhash, to an integer.
  34. """
  35. value = 0
  36. for base83_char in base83_str:
  37. value = value * 83 + alphabet_values[base83_char]
  38. return value
  39. def base83_encode(value, length):
  40. """
  41. Decodes an integer to a base83 string, as used in blurhash.
  42. Length is how long the resulting string should be. Will complain
  43. if the specified length is too short.
  44. """
  45. if int(value) // (83 ** (length)) != 0:
  46. raise ValueError("Specified length is too short to " +
  47. "encode given value.")
  48. result = ""
  49. for i in range(1, length + 1):
  50. digit = int(value) // (83 ** (length - i)) % 83
  51. result += alphabet[int(digit)]
  52. return result
  53. def srgb_to_linear(value):
  54. """
  55. srgb 0-255 integer to linear 0.0-1.0 floating point conversion.
  56. """
  57. value = float(value) / 255.0
  58. if value <= 0.04045:
  59. return value / 12.92
  60. return math.pow((value + 0.055) / 1.055, 2.4)
  61. def sign_pow(value, exp):
  62. """
  63. Sign-preserving exponentiation.
  64. """
  65. return math.copysign(math.pow(abs(value), exp), value)
  66. def linear_to_srgb(value):
  67. """
  68. linear 0.0-1.0 floating point to srgb 0-255 integer conversion.
  69. """
  70. value = max(0.0, min(1.0, value))
  71. if value <= 0.0031308:
  72. return int(value * 12.92 * 255 + 0.5)
  73. return int((1.055 * math.pow(value, 1 / 2.4) - 0.055) * 255 + 0.5)
  74. def blurhash_components(blurhash):
  75. """
  76. Decodes and returns the number of x and y components in the given blurhash.
  77. """
  78. if len(blurhash) < 6:
  79. raise ValueError("BlurHash must be at least 6 characters long.")
  80. # Decode metadata
  81. size_info = base83_decode(blurhash[0])
  82. size_y = int(size_info / 9) + 1
  83. size_x = (size_info % 9) + 1
  84. return size_x, size_y
  85. def blurhash_decode(blurhash, width, height, punch=1.0, linear=False):
  86. """
  87. Decodes the given blurhash to an image of the specified size.
  88. Returns the resulting image a list of lists of 3-value sRGB 8 bit integer
  89. lists. Set linear to True if you would prefer to get linear floating point
  90. RGB back.
  91. The punch parameter can be used to de- or increase the contrast of the
  92. resulting image.
  93. As per the original implementation it is suggested to only decode
  94. to a relatively small size and then scale the result up, as it
  95. basically looks the same anyways.
  96. """
  97. if len(blurhash) < 6:
  98. raise ValueError("BlurHash must be at least 6 characters long.")
  99. # Decode metadata
  100. size_info = base83_decode(blurhash[0])
  101. size_y = int(size_info / 9) + 1
  102. size_x = (size_info % 9) + 1
  103. quant_max_value = base83_decode(blurhash[1])
  104. real_max_value = (float(quant_max_value + 1) / 166.0) * punch
  105. # Make sure we at least have the right number of characters
  106. if len(blurhash) != 4 + 2 * size_x * size_y:
  107. raise ValueError("Invalid BlurHash length.")
  108. # Decode DC component
  109. dc_value = base83_decode(blurhash[2:6])
  110. colours = [(
  111. srgb_to_linear(dc_value >> 16),
  112. srgb_to_linear((dc_value >> 8) & 255),
  113. srgb_to_linear(dc_value & 255)
  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)
  120. / 9.0, 2.0) * real_max_value,
  121. sign_pow((float(int(ac_value / 19) % 19) - 9.0)
  122. / 9.0, 2.0) * real_max_value,
  123. sign_pow((float(ac_value % 19) - 9.0)
  124. / 9.0, 2.0) * real_max_value
  125. ))
  126. # Return image RGB values, as a list of lists of lists,
  127. # consumable by something like numpy or PIL.
  128. pixels = []
  129. for y in range(height):
  130. pixel_row = []
  131. for x in range(width):
  132. pixel = [0.0, 0.0, 0.0]
  133. for j in range(size_y):
  134. for i in range(size_x):
  135. basis = \
  136. math.cos(math.pi * float(x) * float(i) /
  137. float(width)) * \
  138. math.cos(math.pi * float(y) * float(j) / float(height))
  139. colour = colours[i + j * size_x]
  140. pixel[0] += colour[0] * basis
  141. pixel[1] += colour[1] * basis
  142. pixel[2] += colour[2] * basis
  143. if linear is False:
  144. pixel_row.append([
  145. linear_to_srgb(pixel[0]),
  146. linear_to_srgb(pixel[1]),
  147. linear_to_srgb(pixel[2]),
  148. ])
  149. else:
  150. pixel_row.append(pixel)
  151. pixels.append(pixel_row)
  152. return pixels
  153. def blurhash_encode(image, components_x=4, components_y=4, linear=False):
  154. """
  155. Calculates the blurhash for an image using the given x and y
  156. component counts.
  157. Image should be a 3-dimensional array, with the first dimension
  158. being y, the second being x, and the third being the three rgb
  159. components that are assumed to be 0-255 srgb integers
  160. (incidentally, this is the format you will get from a PIL RGB image).
  161. You can also pass in already linear data - to do this, set linear
  162. to True. This is useful if you want to encode a version of your
  163. image resized to a smaller size (which you should ideally do in
  164. linear colour).
  165. """
  166. if components_x < 1 or components_x > 9 or \
  167. components_y < 1 or components_y > 9:
  168. raise ValueError("x and y component counts must be " +
  169. "between 1 and 9 inclusive.")
  170. height = float(len(image))
  171. width = float(len(image[0]))
  172. # Convert to linear if neeeded
  173. image_linear = []
  174. if linear is False:
  175. for y in range(int(height)):
  176. image_linear_line = []
  177. for x in range(int(width)):
  178. image_linear_line.append([
  179. srgb_to_linear(image[y][x][0]),
  180. srgb_to_linear(image[y][x][1]),
  181. srgb_to_linear(image[y][x][2])
  182. ])
  183. image_linear.append(image_linear_line)
  184. else:
  185. image_linear = image
  186. # Calculate components
  187. components = []
  188. max_ac_component = 0.0
  189. for j in range(components_y):
  190. for i in range(components_x):
  191. norm_factor = 1.0 if (i == 0 and j == 0) else 2.0
  192. component = [0.0, 0.0, 0.0]
  193. for y in range(int(height)):
  194. for x in range(int(width)):
  195. basis = \
  196. norm_factor * \
  197. math.cos(math.pi * float(i) * float(x) / width) * \
  198. math.cos(math.pi * float(j) * float(y) / height)
  199. component[0] += basis * image_linear[y][x][0]
  200. component[1] += basis * image_linear[y][x][1]
  201. component[2] += basis * image_linear[y][x][2]
  202. component[0] /= (width * height)
  203. component[1] /= (width * height)
  204. component[2] /= (width * height)
  205. components.append(component)
  206. if not (i == 0 and j == 0):
  207. max_ac_component = \
  208. max(max_ac_component, abs(component[0]),
  209. abs(component[1]), abs(component[2]))
  210. # Encode components
  211. dc_value = (linear_to_srgb(components[0][0]) << 16) + \
  212. (linear_to_srgb(components[0][1]) << 8) + \
  213. linear_to_srgb(components[0][2])
  214. quant_max_ac_component = int(max(0, min(82,
  215. math.floor(max_ac_component *
  216. 166 - 0.5))))
  217. ac_component_norm_factor = float(quant_max_ac_component + 1) / 166.0
  218. ac_values = []
  219. for r, g, b in components[1:]:
  220. r2 = r / ac_component_norm_factor
  221. g2 = g / ac_component_norm_factor
  222. b2 = b / ac_component_norm_factor
  223. r3 = math.floor(sign_pow(r2, 0.5) * 9.0 + 9.5)
  224. g3 = math.floor(sign_pow(g2, 0.5) * 9.0 + 9.5)
  225. b3 = math.floor(sign_pow(b2, 0.5) * 9.0 + 9.5)
  226. ac_values.append(
  227. int(max(0.0, min(18.0, r3))) * 19 * 19 +
  228. int(max(0.0, min(18.0, g3))) * 19 +
  229. int(max(0.0, min(18.0, b3)))
  230. )
  231. # Build final blurhash
  232. blurhash = ""
  233. blurhash += base83_encode((components_x - 1) + (components_y - 1) * 9, 1)
  234. blurhash += base83_encode(quant_max_ac_component, 1)
  235. blurhash += base83_encode(dc_value, 4)
  236. for ac_value in ac_values:
  237. blurhash += base83_encode(ac_value, 2)
  238. return blurhash