BlurHash Python

raw JSON →
1.2.2 verified Fri May 01 auth: no python

A Python implementation of the BlurHash algorithm, which encodes an image into a short, blurry placeholder string. Version 1.2.2 is current, with stable but infrequent releases.

pip install blurhash-python
error TypeError: Argument 'pixels' must be a numpy array with dtype uint8 and shape (height, width, 3)
cause Passing non-numpy data or incorrect dtype/shape to encode().
fix
Ensure pixels is a numpy array: np.array(Image.open('img.jpg')).astype('uint8') and check shape.
error ValueError: Invalid BlurHash: ...
cause Trying to decode an invalid or corrupted BlurHash string.
fix
Verify the BlurHash string has the correct format (e.g., ~LGFO.?-RM{WB?ofV@WB?ofWBof) and was generated by a compatible encoder.
gotcha The encode function expects pixel data as a 3D numpy array with shape (height, width, 3) and dtype uint8. Passing a list or incorrect shape will raise a TypeError.
fix Convert image to a numpy array with dtype uint8 and ensure RGB ordering before calling encode.
gotcha The decode function returns a numpy array of dtype float64, not uint8. Displaying the image requires casting to uint8 and clipping values between 0 and 255.
fix Use decoded_pixels.astype('uint8') before creating an image object.

Encode an image to a BlurHash string and decode it back to a rough placeholder.

from blurhash import encode, decode
from PIL import Image
import numpy as np

img = Image.open('image.jpg').convert('RGB')
arr = np.array(img)
blurhash_str = encode(1920, 1080, arr)
print(blurhash_str)

# Decode back to pixels
pixels = decode(blurhash_str, 32, 32)
recreated = Image.fromarray(pixels.astype('uint8'), 'RGB')
recreated.show()