【python基础】颜色列表和颜色字典以及python画图

发布时间 2023-12-14 18:34:37作者: 鹅要长大

前言

 

使用:

list_keys= [ i for i in cnames.keys()]
list_values= [ i for i in cnames.values()]

 颜色列表示例:

colormap=['#7A57D1','#FF731D','#004d61','#bc8420','#CF0A0A','#83FFE6','#0000A1','#fff568','#0080ff','#81C6E8','#385098','#ffb5ba','#EA047E','#B1AFFF','#425F57','#CFFF8D','#100720','#18978F','#F9CEEE','#7882A4','#E900FF','#84DFFF','#B2EA70','#FED2AA','#49FF00','#14279B','#911F27','#00dffc']

颜色字典示例:

cnames = {
'aliceblue':            '#F0F8FF',
'antiquewhite':         '#FAEBD7',
'aqua':                 '#00FFFF',
'aquamarine':           '#7FFFD4',
'azure':                '#F0FFFF',
'beige':                '#F5F5DC',
'bisque':               '#FFE4C4',
'black':                '#000000',
'blanchedalmond':       '#FFEBCD',
'blue':                 '#0000FF',
'blueviolet':           '#8A2BE2',
'brown':                '#A52A2A',
'burlywood':            '#DEB887',
'cadetblue':            '#5F9EA0',
'chartreuse':           '#7FFF00',
'chocolate':            '#D2691E',
'coral':                '#FF7F50',
'cornflowerblue':       '#6495ED',
'cornsilk':             '#FFF8DC',
'crimson':              '#DC143C',
'cyan':                 '#00FFFF',
'darkblue':             '#00008B',
'darkcyan':             '#008B8B',
'darkgoldenrod':        '#B8860B',
'darkgray':             '#A9A9A9',
'darkgreen':            '#006400',
'darkkhaki':            '#BDB76B',
'darkmagenta':          '#8B008B',
'darkolivegreen':       '#556B2F',
'darkorange':           '#FF8C00',
'darkorchid':           '#9932CC',
'darkred':              '#8B0000',
'darksalmon':           '#E9967A',
'darkseagreen':         '#8FBC8F',
'darkslateblue':        '#483D8B',
'darkslategray':        '#2F4F4F',
'darkturquoise':        '#00CED1',
'darkviolet':           '#9400D3',
'deeppink':             '#FF1493',
'deepskyblue':          '#00BFFF',
'dimgray':              '#696969',
'dodgerblue':           '#1E90FF',
'firebrick':            '#B22222',
'floralwhite':          '#FFFAF0',
'forestgreen':          '#228B22',
'fuchsia':              '#FF00FF',
'gainsboro':            '#DCDCDC',
'ghostwhite':           '#F8F8FF',
'gold':                 '#FFD700',
'goldenrod':            '#DAA520',
'gray':                 '#808080',
'green':                '#008000',
'greenyellow':          '#ADFF2F',
'honeydew':             '#F0FFF0',
'hotpink':              '#FF69B4',
'indianred':            '#CD5C5C',
'indigo':               '#4B0082',
'ivory':                '#FFFFF0',
'khaki':                '#F0E68C',
'lavender':             '#E6E6FA',
'lavenderblush':        '#FFF0F5',
'lawngreen':            '#7CFC00',
'lemonchiffon':         '#FFFACD',
'lightblue':            '#ADD8E6',
'lightcoral':           '#F08080',
'lightcyan':            '#E0FFFF',
'lightgoldenrodyellow': '#FAFAD2',
'lightgreen':           '#90EE90',
'lightgray':            '#D3D3D3',
'lightpink':            '#FFB6C1',
'lightsalmon':          '#FFA07A',
'lightseagreen':        '#20B2AA',
'lightskyblue':         '#87CEFA',
'lightslategray':       '#778899',
'lightsteelblue':       '#B0C4DE',
'lightyellow':          '#FFFFE0',
'lime':                 '#00FF00',
'limegreen':            '#32CD32',
'linen':                '#FAF0E6',
'magenta':              '#FF00FF',
'maroon':               '#800000',
'mediumaquamarine':     '#66CDAA',
'mediumblue':           '#0000CD',
'mediumorchid':         '#BA55D3',
'mediumpurple':         '#9370DB',
'mediumseagreen':       '#3CB371',
'mediumslateblue':      '#7B68EE',
'mediumspringgreen':    '#00FA9A',
'mediumturquoise':      '#48D1CC',
'mediumvioletred':      '#C71585',
'midnightblue':         '#191970',
'mintcream':            '#F5FFFA',
'mistyrose':            '#FFE4E1',
'moccasin':             '#FFE4B5',
'navajowhite':          '#FFDEAD',
'navy':                 '#000080',
'oldlace':              '#FDF5E6',
'olive':                '#808000',
'olivedrab':            '#6B8E23',
'orange':               '#FFA500',
'orangered':            '#FF4500',
'orchid':               '#DA70D6',
'palegoldenrod':        '#EEE8AA',
'palegreen':            '#98FB98',
'paleturquoise':        '#AFEEEE',
'palevioletred':        '#DB7093',
'papayawhip':           '#FFEFD5',
'peachpuff':            '#FFDAB9',
'peru':                 '#CD853F',
'pink':                 '#FFC0CB',
'plum':                 '#DDA0DD',
'powderblue':           '#B0E0E6',
'purple':               '#800080',
'red':                  '#FF0000',
'rosybrown':            '#BC8F8F',
'royalblue':            '#4169E1',
'saddlebrown':          '#8B4513',
'salmon':               '#FA8072',
'sandybrown':           '#FAA460',
'seagreen':             '#2E8B57',
'seashell':             '#FFF5EE',
'sienna':               '#A0522D',
'silver':               '#C0C0C0',
'skyblue':              '#87CEEB',
'slateblue':            '#6A5ACD',
'slategray':            '#708090',
'snow':                 '#FFFAFA',
'springgreen':          '#00FF7F',
'steelblue':            '#4682B4',
'tan':                  '#D2B48C',
'teal':                 '#008080',
'thistle':              '#D8BFD8',
'tomato':               '#FF6347',
'turquoise':            '#40E0D0',
'violet':               '#EE82EE',
'wheat':                '#F5DEB3',
'white':                '#FFFFFF',
'whitesmoke':           '#F5F5F5',
'yellow':               '#FFFF00',
'yellowgreen':          '#9ACD32'}
View Code

根据txt文件画图

# 20231213: show mouth status from mouth log files and then determine the mouth threshold value.
# classid: 0-face, 1-phone, 2-smoke, 3-drink.
# import cv2 as cv
import json
import re
import os
import matplotlib.pyplot as plt
color = ['b', 'g', 'r', 'c', 'm', 'y', 'pueple', 'orange']
cname = ['#7A57D1','#FF731D','#004d61','#bc8420','#CF0A0A','#83FFE6','#0000A1',
         '#fff568','#0080ff','#81C6E8','#385098','#ffb5ba','#EA047E','#B1AFFF',
         '#425F57','#CFFF8D','#100720','#18978F','#F9CEEE','#7882A4','#E900FF',
         '#84DFFF','#B2EA70','#FED2AA','#49FF00','#14279B','#911F27','#00dffc']

font = {'family': 'Times New Roman','size': 12}
font_1 = {'family': 'Times New Roman','size': 16}

def plot_mouthdata(mars, ratios, yawncnts, labelstr):
    xx = list(range(1000))
    fig, ax1 = plt.subplots(figsize=(12,8), dpi=1200)
    # 
    print('plot mar data')
    ax1 = fig.add_subplot(3,1,1)
    # ax1 = plt.subplot(3,1,1)
    fig.tight_layout()
    ax1.plot(xx, [0.5]*len(xx), marker="", markersize=1, alpha=.8, color=cname[-1], linewidth=1, label='thres_0.5', markeredgecolor=cname[-1],)
    ax1.plot(xx, [0.4]*len(xx), marker="", markersize=1, alpha=.8, color=cname[-2], linewidth=1, label='thres_0.4', markeredgecolor=cname[-2],)
    ax1.plot(xx, [0.3]*len(xx), marker="", markersize=1, alpha=.8, color=cname[-3], linewidth=1, label='thres_0.3', markeredgecolor=cname[-3],)
    for i in range(len(labelstr)):
        ax1.plot(xx, mars[i], marker="", markersize=1, alpha=.8, color=cname[i], linewidth=1, label=labelstr[i], markeredgecolor=cname[i],)
    ax1.axis([0, 1000, 0.0, 2.0])
    plt.tick_params(labelsize=14)
    # labels = ax1.get_xticklabels() + ax1.get_yticklabels()
    # [label.set_fontname('Times New Roman') for label in labels]
    plt.rcParams["font.family"] = "Times New Roman"  #全图字号新罗马字体
    plt.legend(ncol=2,frameon=False,prop=font)

    ax1.spines['right'].set_visible(False)
    ax1.spines['top'].set_visible(False)
    plt.xlabel('Frame/f', font_1)
    plt.ylabel('Mar', font_1)
    # 
    print('plot ratio data')
    ax2 = fig.add_subplot(3,1,2)
    ax2 = plt.subplot(3,1,2)
    fig.tight_layout()
    ax2.plot(xx, [0.9]*len(xx), marker="", markersize=1, alpha=.8, color=cname[-1], linewidth=1, label='thres_0.9', markeredgecolor=cname[-1],)
    ax2.plot(xx, [0.7]*len(xx), marker="", markersize=1, alpha=.8, color=cname[-2], linewidth=1, label='thres_0.7', markeredgecolor=cname[-2],)
    ax2.plot(xx, [0.5]*len(xx), marker="", markersize=1, alpha=.8, color=cname[-3], linewidth=1, label='thres_0.5', markeredgecolor=cname[-3],)
    for i in range(len(labelstr)):
        ax2.plot(xx, ratios[i], marker="", markersize=1, alpha=.8, color=cname[i], linewidth=1, label=labelstr[i], markeredgecolor=cname[i],)
    ax2.axis([0, 1000, 0.0, 1.0])
    plt.tick_params(labelsize=14)
    # labels = ax2.get_xticklabels() + ax2.get_yticklabels()
    # [label.set_fontname('Times New Roman') for label in labels]
    plt.rcParams["font.family"] = "Times New Roman"  #全图字号新罗马字体
    plt.legend(ncol=2,frameon=False,prop=font)

    ax2.spines['right'].set_visible(False)
    ax2.spines['top'].set_visible(False)
    plt.xlabel('Frame/f', font_1)
    plt.ylabel('Ratio', font_1)
    #
    print('plot yawncnt data')
    ax3 = fig.add_subplot(3,1,3)
    ax3 = plt.subplot(3,1,3)
    fig.tight_layout()
    for i in range(len(labelstr)):
        ax3.plot(xx, yawncnts[i], marker="", markersize=1, alpha=.8, color=cname[i], linewidth=1, label=labelstr[i], markeredgecolor=cname[i],)
    ax3.axis([0, 1000, 0, 5])
    plt.tick_params(labelsize=14)
    # labels = ax3.get_xticklabels() + ax3.get_yticklabels()
    # [label.set_fontname('Times New Roman') for label in labels]
    plt.rcParams["font.family"] = "Times New Roman"  #全图字号新罗马字体
    plt.legend(ncol=2,frameon=False,prop=font)

    ax3.spines['right'].set_visible(False)
    ax3.spines['top'].set_visible(False)
    plt.xlabel('Frame/f', font_1)
    plt.ylabel('Yawncnt', font_1)
    # 
    plt.savefig('DmsMouthStatus.jpg', dpi=1200)
    plt.savefig('DmsMouthStatus.png', dpi=1200)

def show_mouth_status(path):
    loglist = os.listdir(path)
    fpattern = r'\d+\.\d+'
    dpattern = r'\d+'
    mars = []
    ratios = []
    yawncnts = []
    labels = []
    for i, filename in enumerate(loglist, 1):
        if not filename.endswith('txt'):
            continue
        print('filename: ', filename)
        label = filename.split('_')[2].replace('.txt', '') 
        logfile = open(os.path.join(path, filename), 'r')
        lines = logfile.readlines()
        mar = []
        yawncnt = []
        ratio = []
        for i, line in enumerate(lines, 1):
            if i < 8 or i%2 != 0 or i>2006:
                continue
            # print('line: ', line)
            strl= line.split(',')
            # MAR
            # print('strl: ', strl)
            # print('MAR0: ', re.findall(fpattern, strl[0]))
            # print('MAR1: ', re.findall(dpattern, strl[1]))
            # print('MAR2: ', re.findall(fpattern, strl[2]))
            if (not re.findall(fpattern, strl[0])) and ('MAR' not in strl[0]):
                # print('MAR is None')
                mar.append(None) # NULL
            elif (not re.findall(fpattern, strl[0])) and '0' in strl[0]:
                # print('MAR is 0.0')
                mar.append(0.0)
            elif (not re.findall(fpattern, strl[0])) and '1' in strl[0]:
                # print('MAR is 0.0')
                mar.append(1.0)
            else:
                mar.append(float(re.findall(fpattern, strl[0])[0]))
            # Yawncnt
            yawncnt.append(int(re.findall(dpattern, strl[1])[0]))
            # Ratio
            if not re.findall(fpattern, strl[2]) and ('0' in strl[2]):
                ratio.append(0.0)
            elif (not re.findall(fpattern, strl[2])) and ('1' in strl[2]):
                ratio.append(1.0)
            else:
                ratio.append(float(re.findall(fpattern, strl[2])[0]))
            '''
            fdata = re.findall(fpattern, line) # mar, ratio
            ddata = re.findall(dpattern, line) # yawncnt
            if len(fdata)==1:
                mar.append(None) # NULL
                ratio.append(float(fdata[0]))
                yawncnt.append(int(ddata[1]))
                if int(ddata[1]) > 3:
                    print('---yawn cnt: ', int(ddata[1]))
                    print('---line: ', line)
            else:
                mar.append(float(fdata[0]))
                ratio.append(float(fdata[1]))
                yawncnt.append(int(ddata[2]))
                if int(ddata[2]) > 3:
                    print('yawn cnt: ', int(ddata[2]))
                    print('line: ', line)
                    '''
        mars.append(mar)
        ratios.append(ratio)
        yawncnts.append(yawncnt)
        labels.append(label)
    plot_mouthdata(mars, ratios, yawncnts, labels)

if __name__ == "__main__":
    path = os.path.dirname(os.path.realpath(__file__))
    show_mouth_status(path)
View Code

文件格式(文件名称log_testimg_amy.txt):

-- Join SharedMemory Success. Key Value: 0x36036429
-- Join SharedMemory Success. Key Value: 0x3e036429
-- Join Semaphore Success! Key Value: 0x35036429
-- Join Semaphore Success! Key Value: 0x3d036429
-- Join SharedMemory Success. Key Value: 0x3c036429
-- Join Semaphore Success! Key Value: 0x3b036429
============imgname: /home/root/rjz/dms/testimg/20211220T182058_0000.png
MAR: 0.135135,    getState_slidewin yawncnt: 0,    mouth_open_ratio: 0.002
============imgname: /home/root/rjz/dms/testimg/20211220T182058_0001.png
MAR: 0.141585,    getState_slidewin yawncnt: 0,    mouth_open_ratio: 0.004
.
.
.
============imgname: /home/root/rjz/dms/testimg/20211220T182131_0998.png
MAR: 0.341231,    getState_slidewin yawncnt: 1,    mouth_open_ratio: 0.972
============imgname: /home/root/rjz/dms/testimg/20211220T182131_0999.png
MAR: 0.315143,    getState_slidewin yawncnt: 1,    mouth_open_ratio: 0.972
faces detected num: 1000
faces detected num isDetFaces: 1000
View Code

参考

1. python颜色代码大全,颜色列表|颜色字典 - 孤飞 - 博客园