将图像实例(文件)转换为数组(python)

new*_*ewb 0 python tiff python-imaging-library

我有一个图像序列,我试图在特定的帧上运行脚本.我需要切换到这个框架并将其转换为数组.但是,我无法将框架作为实例<TiffImagePlugin.TiffImageFile image mode=I;16 size=512x512 at 0x104A0C998>.如何将此实例转换为数组?我已经使用过numpy.array但它不起作用.谢谢!

prot=Image.open("F23BN.tif")
for frame in ImageSequence.Iterator(dna):
    if frame==16:
        frame.convert('L')
        print frame.mode, frame.format #I checked the format and it is still in the Instance format
Run Code Online (Sandbox Code Playgroud)

小智 6

据我了解你的问题,你正试图访问tiff图像中包含的二进制数据.正如Dav1d建议你可以在PIL中做到这一点.我在python 2.6.5中测试了以下内容

import Image
import numpy

im = Image.open('Tiff.tif')

imarray = numpy.array(im)
print imarray.shape, im.size   #these agree
Run Code Online (Sandbox Code Playgroud)

对于更难以执行此操作的方法,您可以像打开任何其他文件一样打开文件.在代码片段中,我假设您的文件不是太大,不能一次加载到内存中.

im = open('Tiff.tif','r')
image_data = im.read()
im.close()

#lets look at the first few characters
for char in image_data[:64]:  
    print ord(char),  #need to use ord so we can see the number
Run Code Online (Sandbox Code Playgroud)

使用字符串image_data中的数据,您可以将其转换为您希望的任何其他数据类型.但是,这可能不会立即起作用.首先,数据是二进制的.您需要使用tiff规范对其进行解密.例如,前8个字节是标题.

更多细节:http: //partners.adobe.com/public/developer/en/tiff/TIFF6.pdf