首页 > 解决方案 > 将 TIFF 转换为 numpy 数组

问题描述

我目前正在将 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]]]

我很确定这不能反映图像的信息。关于可能导致此错误的任何想法?如果我不必上传图像文件,我会更喜欢。

标签: pythonimagenumpypython-imaging-librarytiff

解决方案


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

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')

推荐阅读