python - 将 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]]]
我很确定这不能反映图像的信息。关于可能导致此错误的任何想法?如果我不必上传图像文件,我会更喜欢。
解决方案
你的方法对我来说似乎是正确的。下面是一个完美运行的示例。
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')
推荐阅读
- sql - 使用 SQL Server 中关于订单跟踪的“数据透视”将行转换为列
- windows - 当我们尝试删除 kafka 主题时,它只是显示为“标记为删除”
- sql-server - How to import unstructured Excel file into SQL Server (for example with SSIS)?
- json - 数组中的对象未定义
- python - tensorflow setup tool problem while installing in ubuntu16.04 LTS
- jenkins - RTC:每次启动相关的 Jenkins 构建时,工作区都会恢复
- matlab - MATLAB 的 TreeBagger 是否执行交叉验证?
- java - setTableEvent 设置器不再可用于带有 itext7 的表
- python - 在类的 str() 函数中使用实例名称
- python - 机器学习,sklearn kfold,clfs之间的区别在哪里?