Python 如何使用matplotlib读取32位整数图像?
我需要使用Python 2从磁盘读取一个单通道32位整数TIFF图像来执行一些图像分析。我尝试使用matplotlib,但无法使代码正常工作,因为数据被读取为4通道8位整数图像:Python 如何使用matplotlib读取32位整数图像?,python,image,numpy,matplotlib,tiff,Python,Image,Numpy,Matplotlib,Tiff,我需要使用Python 2从磁盘读取一个单通道32位整数TIFF图像来执行一些图像分析。我尝试使用matplotlib,但无法使代码正常工作,因为数据被读取为4通道8位整数图像: >>> import numpy as np >>> import matplotlib.image as mpimg >>> img = mpimg.imread('my_image.tif') >>> img.shape (52, 80, 4)
>>> 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中读取此类图像有其他方法,例如使用from PIL:
>>> 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学习:
>>> from skimage import io
>>> img = io.imread('my_image.tif')
另一种方法是利用OpenCV中的函数。但在这种情况下,数据必须转换为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]])
根据,无法使用matplotlib读取32位整数图像:
Matplotlib plotting可以处理float32和uint8,但除PNG以外的任何格式的图像读/写仅限于uint8数据
作为参考,我在SciPy的基础上找到了另一个解决方法:
from scipy import ndimage
img = ndimage.imread('my_image.tif', mode='I')
基于(由@Warren Weckesser建议的)的方法也很有效:
from tifffile import TiffFile
with TiffFile('my_image.tif') as tif:
img = tif.asarray()
另一种选择是package.Matplotlib主要用于数据可视化,而不是数据生成
imread
是一种方便的功能,但有其局限性。由于有许多专门的图像处理工具可用,因此在matplotlib中不需要此类特殊情况处理。