首页 > 编程语言 >【python基础】颜色列表和颜色字典以及python画图

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

时间:2023-12-14 18:48:49浏览次数:39  
标签:plt ratio python 画图 cname strl 颜色 yawncnt append

前言

 

使用:

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

关键解析数据格式

a='MAR: 0.215604,    getState_slidewin yawncnt: 0,    mouth_open_ratio: 0.002'
b=',    getState_slidewin yawncnt: 0,    mouth_open_ratio: 0.002'
c='MAR: 0.0677596,    getState_slidewin yawncnt: 0,    mouth_open_ratio: 0'
d='MAR: 0,    getState_slidewin yawncnt: 0,    mouth_open_ratio: 0.698'
e='MAR: 0.384575,    getState_slidewin yawncnt: 1,    mouth_open_ratio: 1'
f='MAR: 1,    getState_slidewin yawncnt: 1,    mouth_open_ratio: 0.992'

 

参考

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

标签:plt,ratio,python,画图,cname,strl,颜色,yawncnt,append
From: https://www.cnblogs.com/happyamyhope/p/17900851.html

相关文章

  • Python项目之ATM1.0多模块函数
    ATM1.0多模块【作业】#ATM:提款姬#===================用户功能菜单=====================#1.注册#2.登陆#3.取款#4.转账#5.充值余额#6.查看流......
  • ubuntu 创建一个与系统 python 分离的 python 环境
    为什么需要这样的python环境以免破坏系统python避免和其他用户共用python让python环境私有如何创建这样的环境下载python安装包aptdownloadpython3.8-minimal如果系统提示没有对应的版本,可以试试将3.8修改为其他版本。如果有更好的方法,欢迎留言。下载完成......
  • 12.15----python类
    classUser:def__init__(self,first_name,last_name):"""初始化姓和名"""self.f_name=first_nameself.l_name=last_namedefdescribe_user(self):"""返回整洁的描述性姓名"&q......
  • Python实现软件设计模式2:工厂方法模式
    特点工厂存在父类和子类,产品存在父类和子类。工厂父类负责定义创建产品对象的公共接口,工厂子类负责生成具体的产品对象。包含的角色Product抽象产品ConcreteProduct具体产品Factory抽象工厂ConcreteFactory具体工厂模式分析工厂方法模式是简单工厂模式的进......
  • Python库大全,建议收藏留用!
    学Python,想必大家都是从爬虫开始的吧。毕竟网上类似的资源很丰富,开源项目也非常多。Python学习网络爬虫主要分3个大的版块:抓取,分析,存储当我们在浏览器中输入一个url后回车,后台会发生什么?简单来说这段过程发生了以下四个步骤:查找域名对应的IP地址。向IP对应的服务器发送请求。服务器......
  • Python多线程计算的方法及示例代码
    Python是一种非常流行的编程语言,支持多种并发编程的方式,其中包括多线程。多线程允许程序同时执行多个任务,从而提高了程序的运行效率。下面将介绍Python中多线程计算的几种常见方法,并给出具体的示例代码。方法一:使用标准库threadingPython标准库中提供了threading模块,通过创建Thread......
  • Python项目之ATM1.0单模块函数版
    ATM1.0【作业】#ATM:提款姬#===================用户功能菜单=====================#1.注册#2.登陆#3.取款#4.转账#5.充值余额#6.查看流水#......
  • Python面向对象之抽象类与抽象方法
    C++和Java中面向对象中有抽象类或接口的说法,在python中没有abstract或interface这样的内置关键字。但是abc模块(AbstractBaseClasses)实现了这些抽象类检查的功能,其中ABC是抽象基类。@abstractmethod表示这个方法是一个抽象方法,子类必须重写。关于抽象类与抽象方法的示例代码如下:......
  • python 文件下载快速、安全和简单的方式
    Python文件下载是指使用Python编写的程序来下载文件。给出一个使用urllib库实现文件下载的示例代码:上面的代码中,url变量表示要下载的文件的URL,save_path变量表示文件保存的路径,最后使用urllib.request)函数来下载文件。Python文件下载是指使用Python编写的程序来下载文件。给出一个......
  • 为什么Python赢了,别的语言都干嘛去了?
    为什么Python赢了,别的语言都干嘛去了?作者:刘欣2019-12-0910:00:46企业动态1995年,当JimHugunin正在麻省理工学院和他的硕士论文“搏斗”时,他广泛地使用了Matlab,因为在那篇论文中,他需要对实验结果进行数据分析,和理论值比较。 人工智能时代,为什么Python大放异彩,别的语言都......