blurhash.py 9.7 KB

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