【问题标题】:MatPlotLib Python - RGB values from color sensor used to change color of line pointMatPlotLib Python - 来自颜色传感器的 RGB 值用于更改线点的颜色
【发布时间】:2017-08-12 05:44:34
【问题描述】:

所以我正在使用 TCS3200 颜色传感器和 Arduino Mega 2560 来生成特定的 RGB 值。然后,通过串行电缆,我将数据发送到 VIDLE for Python,拆分 3 个数据点,并将它们存储在一个数组中(每 50 个数据点(每个 RGB)更新一次 MatPlotLib 图。)

最初我在三个单独的线上绘制 R、G、B 值...现在我根据 (255,255,255) 坐标系绘制不同的线(y 限制为 255*sqrt(3)) .

我想要做的是:如果我的 RGB 值为 (220, 60, 140),我希望能够根据这些值更改数据点的颜色。

图形点应该是sqrt(pow(220,2.0)+pow(60,2.0)+pow(140,2.0)),但是颜色需要反映RGB值。

我该怎么做?

这是我当前的绘图设置:

import serial
import numpy as np
import matplotlib.pyplot as plt
from drawnow import *

distance = []
s = serial.Serial(port='/dev/cu.usbmodem1421', baudrate=115200)
plt.ion()
cnt = 0
limit = 255*sqrt(3);
r = 0
g = 0
b = 0

def makeFig():
        plt.ylim(0,limit)
        plt.title('My Live Streaming Sensor Data')
        plt.grid(True)
        plt.ylabel('RGB Values')
        plt.xlabel('Time')
        # somewhere in the line below I think the RGB dynamics should be reflected
        plt.plot(distance, '-', label='Distance')
        plt.ticklabel_format(useOffset=True)
        plt.legend(loc='upper left')

while True:
        while (s.inWaiting()):
               myDataString = s.readline()
               try:
                       dataArray = myDataString.split(',')
                       print (dataArray)
                       r = float(dataArray[0])
                       g = float(dataArray[1])
                       b = float(dataArray[2])
                       d = float(dataArray[3].strip('\r\n')
                       distance.append(d)
                       # before this 'drawnow' gets called, should the RGB values be incorporated into the plot?
                       drawnow(makeFig)
                       plt.pause(0.000001)
                       cnt = cnt + 1
                       if (cnt > 50):
                               distance.pop(0)
               except ValueError:
                       print (myDataString)

【问题讨论】:

  • 查看这篇关于创建可重现示例的文章:stackoverflow.com/help/mcve 只要这个示例依赖于这个神秘的drawnow 包,就没有人能够帮助你。
  • (依赖串行端口获取数据也是如此。用 CSV 文件的StringIO 实例模拟)
  • drawnow 是我见过的最没用的包。它实际上由plt.clf()、函数调用和plt.draw() 组成。但我同意在提出此类问题时应提供minimal reproducible example

标签: python matplotlib linestyle drawnow


【解决方案1】:

这是一种在 RGB 立方体中与原点距离相对应的位置绘制一些点的方法。它们的颜色将设置为 rgb 值元组。

import numpy as np
import matplotlib.pyplot as plt

# Mockup Serial
class Serial():
    n = 0
    def __init__(self, **kwargs):
        self.maxN = kwargs.get("maxN", 1000)
        self.cols = np.arange(0,240,1)
    def inWaiting(self):
        self.n+=1
        return (self.n<self.maxN)
    def readline(self):
        a = np.random.choice(self.cols,size=3)
        a = list(map(str, a))
        b = str(np.random.randint(0,10))
        return ",".join(a)+","+b+'\r\n'

distance = []
colors = []
s = Serial(port='/dev/cu.usbmodem1421', baudrate=115200)
plt.ion()
cnt = 0
limit = 255.*np.sqrt(3)
r = 0
g = 0
b = 0


plt.ylim(0,limit)
plt.title('My Live Streaming Sensor Data')
plt.grid(True)
plt.ylabel('RGB Values')
plt.xlabel('Time')

line,   = plt.plot([],[], '-', color="gray",label='Distance')
scatter  = plt.scatter([],[], s=40, marker='o', label='Hit', zorder=3)
plt.ticklabel_format(useOffset=True)
plt.legend(loc='upper left')


while (s.inWaiting()):
    myDataString = s.readline()
    dataArray = myDataString.split(',')
    r = int(dataArray[0])
    g = int(dataArray[1])
    b = int(dataArray[2])
    d = int(dataArray[3].strip('\r\n'))
    distance.append(np.sqrt(r**2+b**2+g**2))
    color = (r/255.,g/255.,b/255.)
    colors.append(color)
    x = range(len(distance))
    line.set_data(x, distance)
    scatter.set_offsets(np.c_[x,distance])
    scatter.set_color(colors)
    plt.xlim(min(x), max(x))
    plt.pause(0.01)
    cnt = cnt + 1
    if (cnt > 50):
        distance.pop(0)
        colors.pop(0)
    plt.draw()

【讨论】:

  • 我可以生成上面的图表,它看起来非常好。但是,假设 y 轴是 255*sqrt(3) (这是 RGB (255,255,255) 立方体的最大距离/对角线长度),我能否根据每个 RGB 值使这些红点具有不同的颜色绘制第一个时间?
  • 绘制一个新点后,您是否希望所有点都改变颜色?
  • 并非如此。因此,假设绘制的第一个点是基于 RGB (120,60,100)...它的 y 轴值为 ~167,然后下一个点是 (120,80,110)...y 轴 ~181...。 .由点创建的线是正斜率,但点本身是由它们的 RGB 值表示的颜色。如果这很愚蠢,那么我可能会考虑在图表的右上角放置一个大小合适的圆圈,作为颜色显示。
  • 所以每次测量实际上都会产生一个点,而不仅仅是其中一些?点的颜色取决于测量本身?没有愚蠢的事情;一个人只需要精确的要求。
  • 好吧,这可能看起来很愚蠢,从某种意义上说,想象一个难以阅读和观察的图表,其主要焦点可以是任何可以想象的颜色......可能看起来很奇怪。但现在这就是我所追求的。从技术上讲,我有一个按钮可以触发何时捕获数据……但我把它拿出来只是为了确保图形事先可以正常工作。所以是的,现在它每 300 毫秒绘制一次点。点的颜色取决于测量值,是的。
猜你喜欢
  • 1970-01-01
  • 2021-01-07
  • 1970-01-01
  • 2018-01-03
  • 1970-01-01
  • 2023-03-21
  • 2013-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多