lama
75 строк · 2.9 Кб
1import random2import colorsys3
4import numpy as np5import matplotlib6matplotlib.use('agg')7import matplotlib.pyplot as plt8from matplotlib.colors import LinearSegmentedColormap9
10
11def generate_colors(nlabels, type='bright', first_color_black=False, last_color_black=True, verbose=False):12# https://stackoverflow.com/questions/14720331/how-to-generate-random-colors-in-matplotlib13"""14Creates a random colormap to be used together with matplotlib. Useful for segmentation tasks
15:param nlabels: Number of labels (size of colormap)
16:param type: 'bright' for strong colors, 'soft' for pastel colors
17:param first_color_black: Option to use first color as black, True or False
18:param last_color_black: Option to use last color as black, True or False
19:param verbose: Prints the number of labels and shows the colormap. True or False
20:return: colormap for matplotlib
21"""
22if type not in ('bright', 'soft'):23print ('Please choose "bright" or "soft" for type')24return25
26if verbose:27print('Number of labels: ' + str(nlabels))28
29# Generate color map for bright colors, based on hsv30if type == 'bright':31randHSVcolors = [(np.random.uniform(low=0.0, high=1),32np.random.uniform(low=0.2, high=1),33np.random.uniform(low=0.9, high=1)) for i in range(nlabels)]34
35# Convert HSV list to RGB36randRGBcolors = []37for HSVcolor in randHSVcolors:38randRGBcolors.append(colorsys.hsv_to_rgb(HSVcolor[0], HSVcolor[1], HSVcolor[2]))39
40if first_color_black:41randRGBcolors[0] = [0, 0, 0]42
43if last_color_black:44randRGBcolors[-1] = [0, 0, 0]45
46random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels)47
48# Generate soft pastel colors, by limiting the RGB spectrum49if type == 'soft':50low = 0.651high = 0.9552randRGBcolors = [(np.random.uniform(low=low, high=high),53np.random.uniform(low=low, high=high),54np.random.uniform(low=low, high=high)) for i in range(nlabels)]55
56if first_color_black:57randRGBcolors[0] = [0, 0, 0]58
59if last_color_black:60randRGBcolors[-1] = [0, 0, 0]61random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels)62
63# Display colorbar64if verbose:65from matplotlib import colors, colorbar66from matplotlib import pyplot as plt67fig, ax = plt.subplots(1, 1, figsize=(15, 0.5))68
69bounds = np.linspace(0, nlabels, nlabels + 1)70norm = colors.BoundaryNorm(bounds, nlabels)71
72cb = colorbar.ColorbarBase(ax, cmap=random_colormap, norm=norm, spacing='proportional', ticks=None,73boundaries=bounds, format='%1i', orientation=u'horizontal')74
75return randRGBcolors, random_colormap76
77