-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcolormaps.py
63 lines (54 loc) · 2.07 KB
/
colormaps.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# %%
import json
from matplotlib import pyplot as plt
from os import makedirs
from matplotlib.colors import LinearSegmentedColormap, ListedColormap, Colormap
import numpy as np
def export_colormaps(cm_module, folder: str):
makedirs(folder, exist_ok=True)
for name, cmap in vars(cm_module).items():
if not isinstance(cmap, Colormap):
continue
if name.endswith("_r"):
continue
if name.startswith("cmr."):
name = name[4:]
if isinstance(cmap, ListedColormap):
data = cmap(np.linspace(0, 1, 256)).astype(np.float32)
np.save("{}/{}.npy".format(folder, name), data)
elif isinstance(cmap, LinearSegmentedColormap):
segments = cmap._segmentdata
if any(
not isinstance(segments[c], np.ndarray)
and not isinstance(segments[c], list)
and not isinstance(segments[c], tuple)
for c in ["red", "green", "blue"]
):
data = cmap(np.linspace(0, 1, 256)).astype(np.float32)
np.save("{}/{}.npy".format(folder, name), data)
else:
channels = {
c: (
segments[c].tolist()
if isinstance(segments[c], np.ndarray)
else segments[c]
)
for c in ["red", "green", "blue"]
}
if "alpha" in channels:
channels["alpha"] = segments["alpha"].tolist()
with open("{}/{}.json".format(folder, name), "w") as f:
json.dump(
channels,
f,
indent=2,
)
else:
raise TypeError(
"cmap must be either a ListedColormap or a LinearSegmentedColormap"
)
export_colormaps(plt.cm, "colormaps/matplotlib")
import seaborn as sns
export_colormaps(sns.cm, "colormaps/seaborn")
import cmasher
export_colormaps(cmasher.cm, "colormaps/cmasher")