【问题标题】:How to save a 3 channel numpy array as image如何将 3 通道 numpy 数组保存为图像
【发布时间】:2015-02-20 10:21:12
【问题描述】:

我有一个形状为(3, 256, 256) 的 numpy 数组,它是分辨率为 256x256 的 3 通道 (RGB) 图像。我正在尝试通过执行以下操作将 ImagePIL 保存到磁盘:

from PIL import Image
import numpy as np

#... get array s.t. arr.shape = (3,256, 256)
img = Image.fromarray(arr, 'RGB')
img.save('out.png')

但是,这是将尺寸为 256x3 的图像保存到磁盘

【问题讨论】:

  • 您是否尝试过使用np.swapaxes 重塑为(256,256,3) 数组?

标签: python numpy python-imaging-library


【解决方案1】:

你可以使用opencv来合并三个通道并保存为img。

import cv2
import numpy as np
arr = np.random.uniform(size=(3,256,256))*255 # It's a r,g,b array
img = cv2.merge((arr[2], arr[1], arr[0]))  # Use opencv to merge as b,g,r
cv2.imwrite('out.png', img) 

【讨论】:

    【解决方案2】:

    @Dietrich 的答案是有效的,但在某些情况下它会翻转图像。由于转置运算符反转索引,如果图像存储在RGB x rows x cols 中,转置运算符将产生cols x rows x RGB(这是旋转后的图像,而不是所需的结果)。

    >>> arr = np.random.uniform(size=(3,256,257))*255
    

    注意257 以进行可视化。

    >>> arr.T.shape
    (257, 256, 3)
    
    >>> arr.transpose(1, 2, 0).shape
    (256, 257, 3)
    

    最后一个是您在某些情况下可能需要的,因为它会重新排序图像(示例中为rows x cols x RGB),而不是完全转置它。

    >>> arr = np.random.uniform(size=(3,256,256))*255
    >>> arr = np.ascontiguousarray(arr.transpose(1,2,0))
    >>> img = Image.fromarray(arr, 'RGB')
    >>> img.save('out.png')
    

    可能甚至不需要强制转换为连续数组,但最好在保存之前确保图像是连续的。

    【讨论】:

    • 如何将此变量保存为服务器上的图像文件?
    【解决方案3】:

    尝试转置arr,它会为您提供(256, 256, 3) 数组:

    arr = np.random.uniform(size=(3,256,256))*255
    img = Image.fromarray(arr.T, 'RGB')
    img.save('out.png')
    

    【讨论】:

    • 它工作,谢谢,奇怪的是fromarray函数将第三维视为通道数
    猜你喜欢
    • 2020-01-15
    • 1970-01-01
    • 2020-07-07
    • 2010-10-28
    • 2018-03-21
    • 2019-03-15
    • 2011-10-18
    • 1970-01-01
    相关资源
    最近更新 更多