首页 > 解决方案 > 为什么来自 np 数组的 matplotlib 图像以红色为主?

问题描述

我一直在从 np 数组中提取图像数据并添加两个额外的维度,因此我可以使用需要 RGB 数据的图像处理管道,并且图像主要以红色为主。这就是我正在做的事情,从文件路径的数据框开始:

#get filename
f = files.tail(-1)['name'].values[0]
img = plt.imread(f)
#check if it's an array in 3 dimensions
if len(img.shape) == 2:
    print('not RGB')
    #image sizes vary so get shape
    s = img.shape[0:2]
    dim2 = np.zeros((s))
    dim3 = np.zeros((s))
    pix = np.stack((img, dim2,dim3), axis=2)
    pix = np.true_divide(pix, 255)

    plt.imshow(pix)

以及结果样本: 红色图像(应该是黑色/白色)

感谢你的帮助!

标签: pythonmatplotlib

解决方案


以下代码解释了您的问题:

import numpy as np
import matplotlib.pyplot as plt

A = np.random.rand(10, 10)

B = np.zeros((*A.shape, 3))
B[:,:,0] = A

C = A.reshape((*A.shape, 1)).repeat(3, 2)

fig, axs = plt.subplots(ncols=3)

mats = [A, B, C]

for ax, mat in zip(axs, mats):
    ax.imshow(mat)

A是你的灰度图像。B是您所做的:A分配给 RGB 图像的红色通道的值。C很可能是您想要的:由于您需要 RGB 图像,您只需复制A两次的值。结果:

在此处输入图像描述

从左到右:A, B,C


推荐阅读