lama

Форк
0
75 строк · 2.9 Кб
1
import random
2
import colorsys
3

4
import numpy as np
5
import matplotlib
6
matplotlib.use('agg')
7
import matplotlib.pyplot as plt 
8
from matplotlib.colors import LinearSegmentedColormap
9

10

11
def 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-matplotlib
13
    """
14
    Creates 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
    """
22
    if type not in ('bright', 'soft'):
23
        print ('Please choose "bright" or "soft" for type')
24
        return
25

26
    if verbose:
27
        print('Number of labels: ' + str(nlabels))
28

29
    # Generate color map for bright colors, based on hsv
30
    if type == 'bright':
31
        randHSVcolors = [(np.random.uniform(low=0.0, high=1),
32
                          np.random.uniform(low=0.2, high=1),
33
                          np.random.uniform(low=0.9, high=1)) for i in range(nlabels)]
34

35
        # Convert HSV list to RGB
36
        randRGBcolors = []
37
        for HSVcolor in randHSVcolors:
38
            randRGBcolors.append(colorsys.hsv_to_rgb(HSVcolor[0], HSVcolor[1], HSVcolor[2]))
39

40
        if first_color_black:
41
            randRGBcolors[0] = [0, 0, 0]
42

43
        if last_color_black:
44
            randRGBcolors[-1] = [0, 0, 0]
45

46
        random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels)
47

48
    # Generate soft pastel colors, by limiting the RGB spectrum
49
    if type == 'soft':
50
        low = 0.6
51
        high = 0.95
52
        randRGBcolors = [(np.random.uniform(low=low, high=high),
53
                          np.random.uniform(low=low, high=high),
54
                          np.random.uniform(low=low, high=high)) for i in range(nlabels)]
55

56
        if first_color_black:
57
            randRGBcolors[0] = [0, 0, 0]
58

59
        if last_color_black:
60
            randRGBcolors[-1] = [0, 0, 0]
61
        random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels)
62

63
    # Display colorbar
64
    if verbose:
65
        from matplotlib import colors, colorbar
66
        from matplotlib import pyplot as plt
67
        fig, ax = plt.subplots(1, 1, figsize=(15, 0.5))
68

69
        bounds = np.linspace(0, nlabels, nlabels + 1)
70
        norm = colors.BoundaryNorm(bounds, nlabels)
71

72
        cb = colorbar.ColorbarBase(ax, cmap=random_colormap, norm=norm, spacing='proportional', ticks=None,
73
                                   boundaries=bounds, format='%1i', orientation=u'horizontal')
74

75
    return randRGBcolors, random_colormap
76

77

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.