Python讀取和處理分析tif數(shù)據(jù)的超詳細(xì)教程
階段一:基礎(chǔ)篇 - 讀取和查看TIFF數(shù)據(jù)
1. 安裝必要的庫(kù)
首先安裝處理TIFF文件常用的庫(kù):
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. 轉(zhuǎn)換為NumPy數(shù)組進(jìn)行處理
import numpy as np
# 將TIFF圖像轉(zhuǎn)換為NumPy數(shù)組
img_array = np.array(img)
# 打印數(shù)組信息
print(f"數(shù)組形狀: {img_array.shape}")
print(f"數(shù)據(jù)類型: {img_array.dtype}")
print(f"最小值: {img_array.min()}, 最大值: {img_array.max()}")
# 簡(jiǎn)單處理 - 反轉(zhuǎn)圖像
inverted_img = 255 - img_array # 假設(shè)是8位圖像
plt.imshow(inverted_img, cmap='gray')
plt.show()
階段二:中級(jí)篇 - 使用rasterio處理地理TIFF
1. 讀取地理TIFF文件
import rasterio
# 打開地理TIFF文件
with rasterio.open('geospatial.tif') as src:
# 讀取所有波段數(shù)據(jù)
data = src.read()
# 顯示元數(shù)據(jù)
print(f"波段數(shù): {src.count}")
print(f"寬度: {src.width}, 高度: {src.height}")
print(f"坐標(biāo)參考系統(tǒng)(CRS): {src.crs}")
print(f"地理變換: {src.transform}")
# 顯示第一個(gè)波段
plt.imshow(data[0], cmap='viridis')
plt.colorbar()
plt.show()
2. 多波段處理和統(tǒng)計(jì)
with rasterio.open('multiband.tif') as src:
# 讀取各個(gè)波段
red = src.read(1) # 紅波段
green = src.read(2) # 綠波段
blue = src.read(3) # 藍(lán)波段
# 計(jì)算NDVI (假設(shè)第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)
# 顯示裁剪結(jié)果
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)
階段三:高級(jí)篇 - 大型TIFF處理和優(yōu)化
1. 分塊處理大型TIFF
# 使用rasterio的分塊讀取功能
with rasterio.open('very_large.tif') as src:
# 獲取推薦的塊大小
block_shapes = src.block_shapes
print(f"塊大小: {block_shapes}")
# 迭代處理每個(gè)塊
for ji, window in src.block_windows(1):
# 讀取當(dāng)前塊
block = src.read(window=window)
# 處理塊數(shù)據(jù) (示例: 計(jì)算平均值)
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數(shù)組
with rasterio.open('huge.tif') as src:
# 定義塊大小 (例如 1024x1024)
chunk_size = (1, 1024, 1024) # (波段, 高, 寬)
# 創(chuàng)建dask數(shù)組
dask_array = da.from_array(src, chunks=chunk_size)
# 現(xiàn)在可以對(duì)dask數(shù)組執(zhí)行各種操作 (延遲執(zhí)行)
mean_computation = dask_array.mean()
# 實(shí)際計(jì)算結(jié)果 (觸發(fā)計(jì)算)
print(f"整個(gè)圖像的平均值: {mean_computation.compute()}")
3. 并行處理多幅TIFF
from concurrent.futures import ThreadPoolExecutor
import glob
def process_tif(file_path):
"""處理單個(gè)TIFF文件的函數(shù)"""
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))
# 打印結(jié)果
for file_path, mean_val in results:
print(f"{file_path}: {mean_val}")
實(shí)用技巧和小貼士
內(nèi)存管理:
- 對(duì)于大型TIFF,使用
rasterio的窗口讀取或dask進(jìn)行分塊處理 - 處理完成后及時(shí)關(guān)閉文件或使用
with語(yǔ)句
- 對(duì)于大型TIFF,使用
元數(shù)據(jù)保存:
with rasterio.open('input.tif') as src: profile = src.profile # 保存元數(shù)據(jù) # 修改需要的參數(shù) profile.update(dtype=rasterio.float32, count=1) # 寫入新文件時(shí)使用保存的元數(shù)據(jù) with rasterio.open('output.tif', 'w', **profile) as dst: dst.write(processed_data, 1)TIFF格式選擇:
- 地理空間數(shù)據(jù)通常使用GeoTIFF
- 科學(xué)數(shù)據(jù)可能使用BigTIFF (用于>4GB的文件)
- 考慮壓縮選項(xiàng) (DEFLATE, LZW等) 以減小文件大小
性能優(yōu)化:
- 使用
rasterio的window參數(shù)只讀取需要的區(qū)域 - 對(duì)于多波段操作,考慮使用
rasterio的內(nèi)存映射功能 - 對(duì)于重復(fù)讀取相同文件,考慮轉(zhuǎn)換為更適合分析的格式 (如Zarr)
- 使用
總結(jié)
到此這篇關(guān)于Python讀取和處理分析tif數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Python讀取和處理tif數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實(shí)現(xiàn)批量修改xml文件的腳本
這篇文章主要為大家詳細(xì)介紹了如何通過(guò)Python實(shí)現(xiàn)批量修改xml文件功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-11-11
python數(shù)學(xué)模塊(math/decimal模塊)
這篇文章主要介紹了python數(shù)學(xué)模塊(math/decimal模塊),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09
python opencv人臉識(shí)別考勤系統(tǒng)的完整源碼
這篇文章主要介紹了python opencv人臉識(shí)別考勤系統(tǒng)的完整源碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
pytorch中.to(device) 和.cuda()的區(qū)別說(shuō)明
這篇文章主要介紹了pytorch中.to(device) 和.cuda()的區(qū)別說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05
Python tkinter進(jìn)度條控件(Progressbar)的使用
這篇文章主要介紹了Python tkinter進(jìn)度條控件(Progressbar)的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
python爬蟲爬取網(wǎng)頁(yè)數(shù)據(jù)并解析數(shù)據(jù)
這篇文章主要介紹了python爬蟲如何爬取網(wǎng)頁(yè)數(shù)據(jù)并解析數(shù)據(jù),幫助大家更好的利用爬蟲分析網(wǎng)頁(yè),感興趣的朋友可以了解下2020-09-09

