diff --git a/tools/colorize_labels/colorize_labels.py b/tools/colorize_labels/colorize_labels.py index 24e2d61b..409b4195 100644 --- a/tools/colorize_labels/colorize_labels.py +++ b/tools/colorize_labels/colorize_labels.py @@ -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 @@ -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() @@ -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 @@ -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] diff --git a/tools/colorize_labels/test-data/output1.png b/tools/colorize_labels/test-data/output1.png index 5a226afd..b70b94f2 100644 Binary files a/tools/colorize_labels/test-data/output1.png and b/tools/colorize_labels/test-data/output1.png differ diff --git a/tools/colorize_labels/test-data/output2.png b/tools/colorize_labels/test-data/output2.png index d089928b..006ead0b 100644 Binary files a/tools/colorize_labels/test-data/output2.png and b/tools/colorize_labels/test-data/output2.png differ diff --git a/tools/colorize_labels/test-data/output3.png b/tools/colorize_labels/test-data/output3.png new file mode 100644 index 00000000..0e74277a Binary files /dev/null and b/tools/colorize_labels/test-data/output3.png differ