Skip to content

Commit

Permalink
Use variable-length color maps to fix previously failing test
Browse files Browse the repository at this point in the history
  • Loading branch information
kostrykin committed Sep 24, 2024
1 parent 39529ed commit c59405b
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions tools/colorize_labels/colorize_labels.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import argparse

import giatools.io
import matplotlib.colors as mpl
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import scipy.ndimage as ndi
Expand Down Expand Up @@ -43,6 +43,18 @@ def build_label_adjacency_graph(im, radius, bg_label):
return G


def get_n_unique_mpl_colors(n, colormap='jet', cyclic=False):
"""
Yields `n` unique colors from the given `colormap`.
Set `cyclic` to `True` if the `colormap` is cyclic.
"""
cmap = plt.get_cmap(colormap)
m = n if cyclic else n - 1
for i in range(n):
yield np.multiply(255, cmap(i / m))


if __name__ == '__main__':

parser = argparse.ArgumentParser()
Expand All @@ -60,14 +72,13 @@ def build_label_adjacency_graph(im, radius, bg_label):

# Build adjacency graph of the labels
G = build_label_adjacency_graph(im, args.radius, args.bg_label)
print('---')

# Apply greedy coloring
graph_coloring = nx.greedy_color(G)
unique_colors = frozenset(graph_coloring.values())

# Assign colors to nodes based on the greedy coloring
graph_color_to_mpl_color = dict(zip(unique_colors, mpl.TABLEAU_COLORS.values()))
graph_color_to_mpl_color = dict(zip(unique_colors, get_n_unique_mpl_colors(len(unique_colors))))
node_colors = [graph_color_to_mpl_color[graph_coloring[n]] for n in G.nodes()]

# Render result
Expand All @@ -76,7 +87,6 @@ def build_label_adjacency_graph(im, radius, bg_label):
for label, label_color in zip(G.nodes(), node_colors):

cc = (im == label)
label_color = color_hex_to_rgb_tuple(label_color)
for ch in range(3):
result[:, :, ch][cc] = label_color[ch]

Expand Down
Binary file modified tools/colorize_labels/test-data/output1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified tools/colorize_labels/test-data/output2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tools/colorize_labels/test-data/output3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit c59405b

Please sign in to comment.