【发布时间】:2017-04-24 09:25:26
【问题描述】:
我需要使用 Python 2 从磁盘读取单通道 32 位整数 TIFF 图像来执行一些图像分析。我从 matplotlib 尝试了image.imread,但我无法让代码工作,因为数据被读取为 4 通道 8 位整数图像:
>>> import numpy as np
>>> import matplotlib.image as mpimg
>>> img = mpimg.imread('my_image.tif')
>>> img.shape
(52, 80, 4)
>>> img[0:2, 0:2]
array([[[255, 255, 255, 255],
[255, 255, 255, 255]],
[[255, 255, 255, 255],
[255, 255, 255, 255]]], dtype=uint8)
问题:是否可以使用 matplotlib 读取单通道 32 位整数图像?
我知道有其他方法可以在 Python 中读取此类图像,例如使用 PIL 中的Image.open:
>>> from PIL import Image
>>> img = np.asarray(Image.open('my_image.tif'))
>>> img.dtype
dtype('int32')
>>> img.shape
(52, 80)
>>> img[0:2, 0:2]
array([[8745, 8917],
[8918, 9479]])
另一种可能性是使用来自 scikit-learn 的 io.imread:
>>> from skimage import io
>>> img = io.imread('my_image.tif')
另一种方法是利用 OpenCV 中的 imread 函数。但在这种情况下,数据必须转换为 32 位整数:
>>> import cv2
>>> img = cv2.imread('my_image.tif', -1)
>>> img[0:2, 0:2]
array([[ 1.22543551e-41, 1.24953784e-41],
[ 1.24967797e-41, 1.32829081e-41]], dtype=float32)
>>> img.dtype = np.int32
>>> img[0:2, 0:2]
array([[8745, 8917],
[8918, 9479]])
【问题讨论】:
-
另一种选择是tifffile 包。
-
Matplotlib 主要用于数据可视化,而不是用于数据生成。
imread是一个有其局限性的便利功能。由于有很多专门的图像处理工具可用,因此 matplotlib 中不需要这种特殊情况处理。
标签: python image numpy matplotlib tiff