Debian Codegraph @

tests/test_blurhash.py

raw symbols SCIP
1 import sys, os
2 base_path = os.path.dirname(os.path.abspath(__file__))
3 sys.path.insert(0, os.path.join(base_path, '..'))
4
5 import PIL
6 import PIL.Image
7 import blurhash
8 import numpy as np
9 import pytest
10
11 def test_encode():
12 image = PIL.Image.open(os.path.join(base_path, "cool_cat.jpg"))
13 blur_hash = blurhash.encode(np.array(image.convert("RGB")))
14 assert blur_hash == "UBMOZfK1GG%LBBNG,;Rj2skq=eE1s9n4S5Na"
15
16 def test_decode():
17 image = blurhash.decode("UBMOZfK1GG%LBBNG,;Rj2skq=eE1s9n4S5Na", 32, 32)
18 reference_image = np.load(os.path.join(base_path, "blurhash_out.npy"))
19 assert np.sum(np.abs(image - reference_image)) < 1.0
20
21 def test_asymmetric():
22 image = PIL.Image.open(os.path.join(base_path, "cool_cat.jpg"))
23 blur_hash = blurhash.encode(np.array(image.convert("RGB")), components_x = 2, components_y = 8)
24 assert blur_hash == "%BMOZfK1BBNG2skqs9n4?HvgJ.Nav}J-$%sm"
25
26 decoded_image = blurhash.decode(blur_hash, 32, 32)
27 assert np.sum(np.var(decoded_image, axis = 0)) > np.sum(np.var(decoded_image, axis = 1))
28
29 blur_hash = blurhash.encode(np.array(image.convert("RGB")), components_x = 8, components_y = 2)
30 decoded_image = blurhash.decode(blur_hash, 32, 32)
31 assert np.sum(np.var(decoded_image, axis = 0)) < np.sum(np.var(decoded_image, axis = 1))
32
33 def test_components():
34 image = PIL.Image.open(os.path.join(base_path, "cool_cat.jpg"))
35 blur_hash = blurhash.encode(np.array(image.convert("RGB")), components_x = 8, components_y = 3)
36 size_x, size_y = blurhash.components(blur_hash)
37 assert size_x == 8
38 assert size_y == 3
39
40 def test_linear_dc_only():
41 image = PIL.Image.open(os.path.join(base_path, "cool_cat.jpg"))
42 linearish_image = np.array(image.convert("RGB")) / 255.0
43 blur_hash = blurhash.encode(linearish_image, components_x = 1, components_y = 1, linear = True)
44 avg_color = blurhash.decode(blur_hash, 1, 1, linear = True)
45 reference_avg_color = np.mean(linearish_image.reshape(linearish_image.shape[0] * linearish_image.shape[1], -1), 0)
46 assert np.sum(np.abs(avg_color - reference_avg_color)) < 0.01
47
48 def test_invalid_parameters():
49 image = np.array(PIL.Image.open(os.path.join(base_path, "cool_cat.jpg")).convert("RGB"))
50
51 with pytest.raises(ValueError):
52 blurhash.decode("UBMO", 32, 32)
53
54 with pytest.raises(ValueError):
55 blurhash.decode("UBMOZfK1GG%LBBNG", 32, 32)
56
57 with pytest.raises(ValueError):
58 blurhash.encode(image, components_x = 0, components_y = 1)
59
60 with pytest.raises(ValueError):
61 blurhash.encode(image, components_x = 1, components_y = 0)
62
63 with pytest.raises(ValueError):
64 blurhash.encode(image, components_x = 1, components_y = 10)
65
66 with pytest.raises(ValueError):
67 blurhash.encode(image, components_x = 10, components_y = 1)