提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 导入模块
  • TIF文件路径
  • 方法1:tiffile
  • 方法2:PIL
  • 方法3:opencv
  • 方法4:gdal方法1
  • 方法5:gdal方法2

总结Python读取TIF影像的几种方法


导入模块

import numpy as npimport tifffile as tf #tifffile是tiff文件的读取库from PIL import Imageimport cv2 ascvimport gdal

TIF文件路径

path = r'C:/Users/HP/Desktop/tif/jpeg2000/Test_Images/tif/boat4_2100.tif'

方法1:tiffile

img_tf = tf.imread(path)print(img_tf.shape) #(2960, 1976, 3)

方法2:PIL

img = Image.open(path) #可以读取单通道影像,读取3通道16位tif影像时报错(PIL.UnidentifiedImageError: cannot identify image file),支持4通道8位影像arr = np.array(img)print(arr.shape)

方法3:opencv

#arr = cv.imread(path,cv.IMREAD_UNCHANGED)#(2960, 1976)arr = cv.imread(path,1)#(2960, 1976, 3) 备注:4波段的影像在opencv的读取方式中,显示为前三个波段,而且读取顺序为BGRprint(arr.shape)

方法4:gdal方法1

dataset = gdal.Open(path)arr = dataset.ReadAsArray()#(3, 2960, 1976)arr = arr.transpose(1, 2, 0) #(2960, 1976, 3)print(arr.shape)

方法5:gdal方法2

dataset = gdal.Open(path)bands = dataset.RasterCountfor band in range(1, bands + 1):# 读取波段src_band = dataset.GetRasterBand(band)# 波段转数组band_arr = src_band.ReadAsArray()if band == 1:height = band_arr.shape[0]width = band_arr.shape[1]arr = np.zeros((height, width, bands), dtype=np.uint8)arr[:, :, band - 1] = band_arrprint(arr.shape) #(2960, 1976, 3)