将TIFF转换为numpy数组

时间:2018-10-07 19:35:36

标签: python image numpy python-imaging-library tiff

我目前正在将TIFF文件转换为numpy数组。一个简单的工作代码是

from PIL import Image

photo = Image.open("filename.tif")
photo.show()

尽管我确实获得了图片输出,但是却出现了错误

TIFFSetField: tempfile.tif: Unknown pseudo-tag 65538.

此外,当我尝试

data = np.array(photo)
print(data)

我正在获取输出

[[[  0   0   0 255]
  [  0   0   0 255]
  [  0   0   0 255]
  ...
  [  0   0   0 255]
  [  7   7   7 255]
  [  7   7   7 255]]

 [[  0   0   0 255]
  [  0   0   0 255]
  [  0   0   0 255]
  ...
  [  0   0   0 255]
  [  0   0   0 255]
  [  0   0   0 255]]

 [[  5   5   5 255]
  [  0   0   0 255]
  [  0   0   0 255]
  ...
  [  0   0   0 255]
  [  0   0   0 255]
  [  0   0   0 255]]
 ...

 [[  0   0   0 255]
  [  0   0   0 255]
  [  0   0   0 255]
  ...
  [  1   1   1 255]
  [  0   0   0 255]
  [  3   3   3 255]]

 [[  0   0   0 255]
  [  0   0   0 255]
  [  0   0   0 255]
  ...
  [ 11  11  11 255]
  [  0   0   0 255]
  [  0   0   0 255]]]
我很确定

不能反映图像的信息。有什么想法可能导致此错误?如果不需要上传图像文件,我会希望。

1 个答案:

答案 0 :(得分:0)

您的方法对我来说似乎是正确的。下面是一个完美的示例。

In [1]: import numpy as np
In [2]: import PIL
In [3]: from PIL import Image

In [4]: img = Image.open('image.tif')
In [5]: img.show()

In [6]: img_arr = np.array(img)

# 2D array
In [7]: img_arr.shape
Out[7]: (44, 330)

In [8]: img_arr.dtype
Out[8]: dtype('uint8')

In [9]: img_arr
Out[9]: 
array([[  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246],
       ...,
       [  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246]], dtype=uint8)

或者,您也可以使用matplotlib读取图像,如下所示:

In [10]: import matplotlib.pyplot as plt
In [12]: img_ = plt.imread('image.tif')

# 3D array
In [13]: img_.shape
Out[13]: (44, 330, 4)

# PIL image read yields a 2D array instead
In [14]: img_arr.shape
Out[14]: (44, 330)

In [15]: img_.dtype
Out[15]: dtype('uint8')
相关问题