python - 如何将 240*240*4 的 np 数组打印或转换为 240*240*1?

标签 python numpy scipy python-imaging-library

我正在寻找一些我只想打印 np 数组的第一个 channel 的东西。

原始尺寸 = 240*240*4 目标大小 = 240*240*1(仅第一个 channel 。

我在下面尝试过,但似乎确实有效。

image[:,:,:1]

但是以 240*240*1 大小保存回 png 或 jpg 不起作用

示例代码

import numpy as np
from PIL import Image
import scipy.misc as sp
image = np.array(Image.open("FLAIR-148.png"))
test_image = image[:,:,:1]
sp.imsave('out.png', test_image)

输出

File "/anaconda3/lib/python3.6/site-packages/scipy/misc/pilutil.py", line 327, in toimage
raise ValueError("'arr' does not have a suitable array shape for "
ValueError: 'arr' does not have a suitable array shape for any mode.

最佳答案

如果您不切片最后一个索引(即执行 image[:, :, 1]),那么一切都应该正常工作:

import numpy as np
from PIL import Image
import scipy.misc as smc

image = np.array(Image.open("FLAIR-148.png"))
test_image = image[:, :, 1]
smc.imsave('out.png', test_image)

基本上,scipy.misc.imsave 不知道如何处理形状(M, N, 1) 的数组。但是,它确实知道应该将形状为 (M, N) 的数组保存为灰度图像。

您可能还需要将数组转换为 uint8 以确保结果一致。这是一个完整的最小示例:

import scipy.misc as smc

# get the test image as an array
img = smc.face()

# slice test image
img = img[:, :, 1]

# convert to uint8
img = img.astype('uint8')

# save
smc.imsave('test.png', img)

输出:

enter image description here

警告

scipy.misc.imsave is deprecated 。建议使用imageio.imwrite相反。

关于python - 如何将 240*240*4 的 np 数组打印或转换为 240*240*1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54207293/

相关文章:

python - AWS 胶水 : How to expand nested Hive struct to Dict?

python - Pyspark groupby 并返回整行

python - Cythonized 函数出乎意料地慢

python - 为什么 numpy 比 for 循环慢

python - 在 Python numpy 掩码数组中用最近的邻居填充缺失值?

python - 如何在 SymPy 中使用 Galois 域上的多项式

python - 我如何使用 Django objects.filter 执行此操作?

python - numpy 数组转换成对

python - 使用python生成数据簇?

python - 做ILP时的多种解决方案