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

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

文章目录

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

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


导入模块

import numpy as np
import tifffile as tf           #tifffile是tiff文件的读取库
from PIL import Image
import cv2 as  cv
import 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的读取方式中,显示为前三个波段,而且读取顺序为BGR
print(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.RasterCount
for 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_arr
print(arr.shape)                     #(2960, 1976, 3)


你可能感兴趣的:(遥感图像处理,python,opencv,图像处理)