You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib显示RGB像素异常,呈现分离色块问题求助

问题描述

从图像中提取了一组RGB像素值,但保存并显示时画面呈现三个分离的色块,程序未将数组识别为RGB值列表。

简化后的代码示例:

import matplotlib.pyplot as plt
import numpy as np

img = np.array([[255, 255, 255], [127, 255, 127], [239, 255,  15], [127 ,  0,   0]])

plt.imshow(img)
plt.savefig('testtt.png', dpi=400)

运行代码得到的异常图像:
异常显示的图像

请问如何解决该问题?问题出在哪里?有没有更好的无需使用OpenCV的RGB像素数组显示方法?


问题原因
  • 你的数组形状为(4, 3),matplotlib会将其判定为4行3列的单通道灰度图像,每个子列表被当作一行的灰度值,因此显示出3列色块。
  • 数组默认类型为int64,matplotlib会对该类型图像自动做归一化处理,进一步导致颜色显示异常。
解决方法

方法1:调整数组形状并指定数据类型

matplotlib要求RGB图像的形状为(高度, 宽度, 3),同时需使用uint8类型(匹配RGB像素0-255的标准范围)。如果要横向排列4个像素,可将数组转为(1, 4, 3)的形状:

import matplotlib.pyplot as plt
import numpy as np

# 调整形状为(1行, 4列, 3通道),并转为uint8类型
img = np.array([[255, 255, 255], [127, 255, 127], [239, 255, 15], [127, 0, 0]], dtype=np.uint8).reshape(1, 4, 3)

plt.imshow(img)
plt.savefig('testtt.png', dpi=400)
plt.show()

若要纵向排列像素,只需将形状改为(4, 1, 3)即可。

方法2:使用PIL库(无需OpenCV)

PIL库处理像素数组更直观,直接按像素排列创建图像:

from PIL import Image
import numpy as np

# 转为uint8类型,调整为(1行, 4列, 3通道)的形状
img_array = np.array([[255, 255, 255], [127, 255, 127], [239, 255, 15], [127, 0, 0]], dtype=np.uint8).reshape(1, 4, 3)
# 创建图像并保存、显示
img = Image.fromarray(img_array)
img.save('testtt.png')
img.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:05:23