【问题标题】:python make RGB image from 3 float32 numpy arrayspython从3个float32 numpy数组制作RGB图像
【发布时间】:2015-01-11 03:49:57
【问题描述】:

我有 3 个 400x600 的数组,它们代表我想要制作的图像的 3 种颜色。

我在这里找到了一种潜在的方法:http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/scipy.misc.imsave.html 但他们希望我将浮点数转换为 uint8。现在,如果我通过 'image.dtype = np.uint8' 更改 dtype,然后以某种方式将尺寸更改为 400x600x24(而当我不更改类型时,它是 400x600x3)

我该如何更改? (也欢迎其他方法)

【问题讨论】:

    标签: python arrays image scipy rgb


    【解决方案1】:

    image.dtype = np.uint8 只是将字节从float64 强制转换为uint8。由于每个 float64 占用 8 个字节,而每个 uint8 仅占用 1 个字节,因此您将获得 8 倍的值。

    要转换值,而不是重新解释字节,您需要astype 方法:

    image = image.astype(np.uint8)
    

    但是,这可能不会很有用,原因有两个。首先,大的,您的浮点值可能都在 0.0-1.0 范围内。其次,astype 截断,而不是四舍五入。因此,转换为整数只会使它们几乎全部为 0,其余为 1,而不是平滑地从 0 到 255。

    所以,你可能想要的是这样的:

    image = (image * 255).round().astype(np.uint8)
    

    【讨论】:

      【解决方案2】:

      谢谢@abarnert!这就是我要从 sklearn.datasets.fetch_olivetti_faces() 之类的数据集中加载图像的内容,该数据集具有 dtypefloat32 和值范围从 0-1 以与使用 dtype 的 OpenCV 一起使用987654324@,取值范围为 0-255。

      import numpy as np
      import cv2 as cv
      from sklearn import datasets
      
      data = datasets.fetch_olivetti_faces()
      image = data.images[15]
      image
      

      array([[0.6694215 , 0.6818182 , 0.7066116 , ..., 0.5082645 , 0.55785125, 0.58677685], [0.677686, 0.70247936, 0.71487606, ..., 0.5289256, 0.5495868, 0.58264464], [0.6983471, 0.7107438, 0.70247936, ..., 0.5495868, 0.55785125, 0.5785124], ..., [0.59917355, 0.59917355, 0.54545456, ..., 0.10743801, 0.11157025, 0.10330579], [0.59090906, 0.6198347, 0.5785124, ..., 0.11157025, 0.10743801, 0.10743801], [0.5661157, 0.6280992, 0.59917355, ..., 0.11157025, 0.11157025, 0.10743801]], dtype=float32)

      img = (image * 255).round().astype(np.uint8)
      img
      

      array([[171, 174, 180, ..., 130, 142, 150], [173, 179, 182, ..., 135, 140, 149], [178, 181, 179, ..., 140, 142, 148], ..., [153, 153, 139, ..., 27, 28, 26], [151, 158, 148, ..., 28, 27, 27], [144, 160, 153, ..., 28, 28, 27]], dtype=uint8)

      img 现在已准备好在 cv 库中进行进一步处理。

      【讨论】:

        猜你喜欢
        • 2012-05-13
        • 1970-01-01
        • 2016-08-26
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-16
        相关资源
        最近更新 更多