You need to enable JavaScript to run this app. Matplotlib创建指定RGB背景色空白图时背景为白如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib创建指定RGB背景色空白图时背景为白如何解决?

问题根源

你创建的numpy矩阵M默认是浮点类型,而matplotlib的imshow对RGB输入的取值范围有明确要求:

  • 浮点型RGB数据:取值范围必须在[0, 1]之间
  • 整数型RGB数据:取值范围必须在[0, 255]之间

你给浮点矩阵赋值了200,远超浮点RGB的合法上限1,所有超过1的数值都会被裁剪为1,三个通道都为1对应就是纯白色,和你收到的裁剪提示完全对应。


解决方法1:调整浮点数值到合法范围

把RGB值统一除以255,缩放到0-1区间即可:

import numpy as np
import matplotlib.pyplot as plt

M = np.zeros(shape=(960, 1280, 3))
M[:, :,] = np.array([200, 200, 200]) / 255 # 除以255缩放到0-1范围

print(M.shape)

plt.imshow(M)

for point in [[200, 200], [1200, 600], [1200, 800], [200, 400]]:
    x = point[0]
    y = point[1]
    plt.plot(x, y, marker='o', markersize=5)

plt.grid()
plt.show()

解决方法2:将矩阵转为整数类型

直接把矩阵指定为uint8(8位无符号整数)类型,就可以直接使用0-255的RGB值:

import numpy as np
import matplotlib.pyplot as plt

# 创建矩阵时直接指定为uint8类型
M = np.zeros(shape=(960, 1280, 3), dtype=np.uint8)
M[:, :,] = np.array([200, 200, 200], dtype=np.uint8)

print(M.shape)

plt.imshow(M)

for point in [[200, 200], [1200, 600], [1200, 800], [200, 400]]:
    x = point[0]
    y = point[1]
    plt.plot(x, y, marker='o', markersize=5)

plt.grid()
plt.show()

内容的提问来源于stack exchange,提问作者stackoverflowuser2010

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 22:54:03