Python讀取和處理分析tif數據的超詳細教程
更新時間:2025年11月15日 08:31:05 作者:請一直在路上
TIF格式是一種跨平臺的圖片格式,可同時支持Windows和Mac系統(tǒng)的操作,TIF格式可以在保證圖片不失真的情況下壓縮,且保留圖片的分層或是透明信息,這篇文章主要介紹了Python讀取和處理分析tif數據的相關資料,需要的朋友可以參考下
階段一:基礎篇 - 讀取和查看TIFF數據
1. 安裝必要的庫
首先安裝處理TIFF文件常用的庫:
pip install pillow numpy matplotlib rasterio
2. 使用Pillow讀取TIFF文件
from PIL import Image
import matplotlib.pyplot as plt
# 打開TIFF文件
img = Image.open('example.tif')
# 顯示基本信息
print(f"格式: {img.format}")
print(f"大小: {img.size}")
print(f"模式: {img.mode}")
# 顯示圖像
plt.imshow(img)
plt.show()
3. 轉換為NumPy數組進行處理
import numpy as np
# 將TIFF圖像轉換為NumPy數組
img_array = np.array(img)
# 打印數組信息
print(f"數組形狀: {img_array.shape}")
print(f"數據類型: {img_array.dtype}")
print(f"最小值: {img_array.min()}, 最大值: {img_array.max()}")
# 簡單處理 - 反轉圖像
inverted_img = 255 - img_array # 假設是8位圖像
plt.imshow(inverted_img, cmap='gray')
plt.show()
階段二:中級篇 - 使用rasterio處理地理TIFF
1. 讀取地理TIFF文件
import rasterio
# 打開地理TIFF文件
with rasterio.open('geospatial.tif') as src:
# 讀取所有波段數據
data = src.read()
# 顯示元數據
print(f"波段數: {src.count}")
print(f"寬度: {src.width}, 高度: {src.height}")
print(f"坐標參考系統(tǒng)(CRS): {src.crs}")
print(f"地理變換: {src.transform}")
# 顯示第一個波段
plt.imshow(data[0], cmap='viridis')
plt.colorbar()
plt.show()
2. 多波段處理和統(tǒng)計
with rasterio.open('multiband.tif') as src:
# 讀取各個波段
red = src.read(1) # 紅波段
green = src.read(2) # 綠波段
blue = src.read(3) # 藍波段
# 計算NDVI (假設第4波段是近紅外)
nir = src.read(4)
ndvi = (nir - red) / (nir + red + 1e-10) # 避免除以0
# 顯示NDVI
plt.imshow(ndvi, cmap='RdYlGn', vmin=-1, vmax=1)
plt.colorbar(label='NDVI')
plt.title('NDVI Map')
plt.show()
3. 裁剪和重投影
from rasterio.warp import calculate_default_transform, reproject, Resampling
# 裁剪示例
with rasterio.open('large_image.tif') as src:
# 定義裁剪窗口 (左上x, 左上y, 右下x, 右下y)
window = rasterio.windows.Window(1000, 1000, 500, 500)
clipped = src.read(window=window)
# 顯示裁剪結果
plt.imshow(clipped[0])
plt.show()
# 重投影示例
dst_crs = 'EPSG:3857' # Web墨卡托投影
with rasterio.open('input.tif') as src:
transform, width, height = calculate_default_transform(
src.crs, dst_crs, src.width, src.height, *src.bounds)
kwargs = src.meta.copy()
kwargs.update({
'crs': dst_crs,
'transform': transform,
'width': width,
'height': height
})
with rasterio.open('reprojected.tif', 'w', **kwargs) as dst:
for i in range(1, src.count + 1):
reproject(
source=rasterio.band(src, i),
destination=rasterio.band(dst, i),
src_transform=src.transform,
src_crs=src.crs,
dst_transform=transform,
dst_crs=dst_crs,
resampling=Resampling.nearest)
階段三:高級篇 - 大型TIFF處理和優(yōu)化
1. 分塊處理大型TIFF
# 使用rasterio的分塊讀取功能
with rasterio.open('very_large.tif') as src:
# 獲取推薦的塊大小
block_shapes = src.block_shapes
print(f"塊大小: {block_shapes}")
# 迭代處理每個塊
for ji, window in src.block_windows(1):
# 讀取當前塊
block = src.read(window=window)
# 處理塊數據 (示例: 計算平均值)
block_mean = np.mean(block)
print(f"塊 {ji} 的平均值: {block_mean}")
# 這里可以添加你的處理邏輯
# processed_block = some_processing(block)
# 寫入輸出文件 (如果需要)
# dst.write(processed_block, window=window)
2. 使用Dask處理超大型TIFF
import dask.array as da
import rasterio
from rasterio.windows import Window
# 創(chuàng)建延遲加載的dask數組
with rasterio.open('huge.tif') as src:
# 定義塊大小 (例如 1024x1024)
chunk_size = (1, 1024, 1024) # (波段, 高, 寬)
# 創(chuàng)建dask數組
dask_array = da.from_array(src, chunks=chunk_size)
# 現在可以對dask數組執(zhí)行各種操作 (延遲執(zhí)行)
mean_computation = dask_array.mean()
# 實際計算結果 (觸發(fā)計算)
print(f"整個圖像的平均值: {mean_computation.compute()}")
3. 并行處理多幅TIFF
from concurrent.futures import ThreadPoolExecutor
import glob
def process_tif(file_path):
"""處理單個TIFF文件的函數"""
with rasterio.open(file_path) as src:
data = src.read(1)
# 這里添加你的處理邏輯
result = np.mean(data)
return file_path, result
# 獲取所有TIFF文件
tif_files = glob.glob('data/*.tif')
# 使用線程池并行處理
with ThreadPoolExecutor(max_workers=4) as executor:
results = list(executor.map(process_tif, tif_files))
# 打印結果
for file_path, mean_val in results:
print(f"{file_path}: {mean_val}")
實用技巧和小貼士
內存管理:
- 對于大型TIFF,使用
rasterio的窗口讀取或dask進行分塊處理 - 處理完成后及時關閉文件或使用
with語句
- 對于大型TIFF,使用
元數據保存:
with rasterio.open('input.tif') as src: profile = src.profile # 保存元數據 # 修改需要的參數 profile.update(dtype=rasterio.float32, count=1) # 寫入新文件時使用保存的元數據 with rasterio.open('output.tif', 'w', **profile) as dst: dst.write(processed_data, 1)TIFF格式選擇:
- 地理空間數據通常使用GeoTIFF
- 科學數據可能使用BigTIFF (用于>4GB的文件)
- 考慮壓縮選項 (DEFLATE, LZW等) 以減小文件大小
性能優(yōu)化:
- 使用
rasterio的window參數只讀取需要的區(qū)域 - 對于多波段操作,考慮使用
rasterio的內存映射功能 - 對于重復讀取相同文件,考慮轉換為更適合分析的格式 (如Zarr)
- 使用
總結
到此這篇關于Python讀取和處理分析tif數據的文章就介紹到這了,更多相關Python讀取和處理tif數據內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python opencv人臉識別考勤系統(tǒng)的完整源碼
這篇文章主要介紹了python opencv人臉識別考勤系統(tǒng)的完整源碼,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04
pytorch中.to(device) 和.cuda()的區(qū)別說明
這篇文章主要介紹了pytorch中.to(device) 和.cuda()的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
Python tkinter進度條控件(Progressbar)的使用
這篇文章主要介紹了Python tkinter進度條控件(Progressbar)的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-04-04

