使用Python读取16位PNG图像文件 [英] Read 16-bit PNG image file using Python
问题描述
我正在尝试读取以16位数据类型编写的PNG图像文件.数据应转换为NumPy数组.但是我不知道如何读取"16位"文件.我尝试使用PIL和SciPy,但它们在加载时将16位数据转换为8位.有人可以让我知道如何在不更改数据类型的情况下从16位PNG文件中提取数据并将其转换为NumPy数组吗?
I'm trying to read a PNG image file written in 16-bit data type. The data should be converted to a NumPy array. But I have no idea how to read the file in '16-bit'. I tried with PIL and SciPy, but they converted the 16-bit data to 8-bit when they load it. Could anyone please let me know how to up out data from a 16-bit PNG file and convert it to NumPy array without changing the datatype?
以下是我使用的脚本.
The following is the script I used.
from scipy import misc
import numpy as np
from PIL import Image
#make a png file
a = np.zeros((1304,960), dtype=np.uint16)
a[:] = np.arange(960)
misc.imsave('16bit.png',a)
#read the png file using scipy
b = misc.imread('16bit.png')
print "scipy:" ,b.dtype
#read the png file using PIL
c = Image.open('16bit.png')
d = np.array(c)
print "PIL:", d.dtype
推荐答案
我在这里有同样的问题.即使使用我自己创建的16位图像,我也进行了测试.当我用png包加载它们时,它们都正确打开了.而且'file'的输出看起来还不错.
I have the same problem here. I tested it even with 16 bit images i created by my own. All of them were opened correctly when i loaded them with the png package. Also the output of 'file ' looked okay.
使用PIL打开它们总是会导致8位numpy数组.
Opening them with PIL always led to 8-bit numpy-arrays.
在Linux btw上使用Python 2.7.6.
Working with Python 2.7.6 on Linux btw.
像这样对我有用:
import png
import numpy as np
reader = png.Reader( path-to-16bit-png )
pngdata = reader.read()
px_array = np.array( map( np.uint16, pngdata[2] )
print( px_array.dtype )
也许有人可以提供更多信息,在哪种情况下,前一种方法行得通? (因为这个速度很慢)
Maybe someone can give more information under which circumstances the former approach worked? (as this one is pretty slow)
提前谢谢.
这篇关于使用Python读取16位PNG图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!