imshow 未显示正确的 RGB 值

问题描述 投票:0回答:1

我很困惑为什么我的画布类只产生

255
颜色,在这种情况下是纯红色的颜色。

虽然我的代码为不同像素的颜色指定了较深的红色调,但代码下方链接的结果图像显示每个像素的颜色相同。

要重现的代码。

class Canvas():
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.pixels = np.zeros((y,x,3))

    def _center2pixel(self, x, y):
        return (self.y//2 - y, self.x//2 + x)

    def write_pixel(self, x, y, color):
        x,y = self._center2pixel(x,y)
        self.pixels[x,y] = color

    def show(self):
        plt.imshow(self.pixels, vmin=0, vmax=255)
        plt.show()

    
canvas = Canvas(10,10)


canvas.write_pixel(0,0,np.array([255,0,0])*0.1)
canvas.write_pixel(1,0,np.array([255,0,0]))
canvas.write_pixel(2,0,np.array([10,0,0]))
canvas.write_pixel(3,0,np.array([25.5,0,0]))
canvas.show()

4 pixels with the same color value although they were designed to have different color values

你能帮我解决这个问题吗?我做错了什么?

此外,我收到一条警告,指出它已剪切输入,并且它应该在 0 到 255 之间 - 确实如此。

我尝试指定不同的颜色,但绘图上显示相同的颜色。

python matplotlib imshow
1个回答
0
投票

所有数组都包含浮点数,这是 numpy 的默认值。当您使用 RGB 浮点数时,它们必须介于 0 和 1 之间,这正是错误消息告诉您的内容。您的值都大于 1,因此完全饱和。

你有两个选择。使用

dtype=np.uint8
将颜色转换为整数,或将范围更改为 [0,1]:

canvas.write_pixel(0,0,np.array([1,0,0])*0.1)
canvas.write_pixel(1,0,np.array([1,0,0]))
canvas.write_pixel(2,0,np.array([0.04,0,0]))
canvas.write_pixel(3,0,np.array([0.1,0,0]))
© www.soinside.com 2019 - 2024. All rights reserved.