将numpy数组保存为图像

将numpy数组保存为图像

本文介绍了使用scikit-image以高精度(16位)将numpy数组保存为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用2D浮点numpy数组,我希望将其保存为具有高精度(例如16位)的灰度.png文件。如果可能的话,我想使用scikit-image skimage.io 包。

I am working with 2D floating-point numpy arrays that I would like to save to greyscale .png files with high precision (e.g. 16 bits). I would like to do this using the scikit-image skimage.io package if possible.

这是主要的事情我试过了:

Here's the main thing I've tried:

import numpy as np
from skimage import io, exposure, img_as_uint, img_as_float

im = np.array([[1., 2.], [3., 4.]], dtype='float64')
im = exposure.rescale_intensity(im, out_range='float')
im = img_as_uint(im)
im

产生:

array([[    0, 21845],
       [43690, 65535]], dtype=uint16)

首先我尝试将其保存为图像,然后使用Python Imaging Library重新加载:

First I tried saving this as an image then reloading using the Python Imaging Library:

# try with pil:
io.use_plugin('pil')
io.imsave('test_16bit.png', im)
im2 = io.imread('test_16bit.png')
im2

产生:

array([[  0,  85],
       [170, 255]], dtype=uint8)

所以某处(写入或读取)我失去了精确度。然后我尝试使用matplotlib插件:

So somewhere (in either the write or read) I have lost precision. I then tried with the matplotlib plugin:

# try with matplotlib:
io.use_plugin('matplotlib')
io.imsave('test_16bit.png', im)
im3 = io.imread('test_16bit.png')
im3

给我一​​个32位浮点数:

gives me a 32-bit float:

array([[ 0.        ,  0.33333334],
       [ 0.66666669,  1.        ]], dtype=float32)

但我怀疑这是32位,因为我保存了16位uint到文件。如果有人能指出我出错的地方会很棒。我希望这也扩展到3D数组(即每个颜色通道保存16位,每个图像48位)。

but I doubt this is really 32-bits given that I saved a 16-bit uint to the file. It would be great if someone could point me to where I'm going wrong. I would like this to extend to 3D arrays too (i.e. saving 16 bits per colour channel, for 48 bits per image).

问题在于imsave。图像是每通道8位。如何使用io.imsave输出高位深度图像?

The problem is with imsave. The images are 8 bits per channel. How can one use io.imsave to output a high bit-depth image?

推荐答案

您想使用 freeimage 库来执行此操作:

You wanna use the freeimage library to do so:

import numpy as np
from skimage import io, exposure, img_as_uint, img_as_float

io.use_plugin('freeimage')

im = np.array([[1., 2.], [3., 4.]], dtype='float64')
im = exposure.rescale_intensity(im, out_range='float')
im = img_as_uint(im)

io.imsave('test_16bit.png', im)
im2 = io.imread('test_16bit.png')

结果:

[[    0 21845]
 [43690 65535]]

对于3D数组,你需要正确构造数组然后它才能工作:

As for 3D arrays, you need to construct the array properly and then it'll work:

# im = np.array([[1, 2.], [3., 4.]], dtype='float64')
im = np.linspace(0, 1., 300).reshape(10, 10, 3)
im = exposure.rescale_intensity(im, out_range='float')
im = img_as_uint(im)

io.imsave('test_16bit.png', im)
im2 = io.imread('test_16bit.png')

注意读取的图像被翻转,所以像 np.fliplr(np.flipud(im2))这样会使它变成原始形状。

Note that the read image is flipped, so something like np.fliplr(np.flipud(im2)) will bring it to original shape.

这篇关于使用scikit-image以高精度(16位)将numpy数组保存为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 17:31