Skip to content

Commit

Permalink
better cmaps
Browse files Browse the repository at this point in the history
  • Loading branch information
KeKsBoTer committed May 16, 2024
1 parent d30ce46 commit 1cf012c
Show file tree
Hide file tree
Showing 9 changed files with 276 additions and 117 deletions.
92 changes: 54 additions & 38 deletions colormaps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,62 @@
import json
from matplotlib import pyplot as plt
from os import makedirs
from matplotlib.colors import LinearSegmentedColormap, ListedColormap
from matplotlib.colors import LinearSegmentedColormap, ListedColormap, Colormap
import numpy as np

makedirs("colormaps", exist_ok=True)
for name in plt.colormaps():
cmap = plt.get_cmap(name)
if isinstance(cmap, ListedColormap):
data = cmap(np.linspace(0, 1, 256)).astype(np.float32)
np.save("colormaps/{}.npy".format(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"]
):

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("colormaps/{}.npy".format(name), data)
else:
channels = {
c: (
segments[c].tolist()
if isinstance(segments[c], np.ndarray)
else segments[c]
)
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"]
}
if "alpha" in channels:
channels["alpha"] = segments["alpha"].tolist()
with open("colormaps/{}.json".format(name), "w") as f:
json.dump(
channels,
f,
indent=2,
)
else:
raise TypeError(
"cmap must be either a ListedColormap or a LinearSegmentedColormap"
)
):
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")
4 changes: 3 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
matplotlib
numpy
numpy
seaborn
cmasher
4 changes: 2 additions & 2 deletions src/bin/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use cgmath::Vector2;
use clap::Parser;

use std::{fs::File, path::PathBuf};
use v4dv::cmap::ColorMapType;
use v4dv::cmap::GenericColorMap;
use v4dv::volume::Volume;

#[derive(Debug, Parser)]
Expand Down Expand Up @@ -54,7 +54,7 @@ async fn main() -> anyhow::Result<()> {
let volume_file = File::open(&opt.input)?;
let cmap_file = File::open(opt.colormap)?;
let volumes = Volume::load_numpy(volume_file, opt.channel_first)?;
let cmap = ColorMapType::read(cmap_file)?;
let cmap = GenericColorMap::read(cmap_file)?;

let resolution = Vector2::new(opt.width, opt.height);

Expand Down
4 changes: 2 additions & 2 deletions src/bin/viewer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ async fn main() -> anyhow::Result<()> {
.expect("Failed to load volume");

#[cfg(feature = "colormaps")]
let cmap = cmap::COLORMAPS.get("summer").unwrap().clone();
let cmap = cmap::COLORMAPS["matplotlib"]["viridis"].clone();
#[cfg(not(feature = "colormaps"))]
let cmap = {
let reader = File::open(&opt.colormap)?;
cmap::ColorMapType::read(reader)?
cmap::GenericColorMap::read(reader)?
};

open_window(
Expand Down
Loading

0 comments on commit 1cf012c

Please sign in to comment.