前言
為了創(chuàng)建深度學(xué)習(xí)的樣本,需要做一個(gè)512*512標(biāo)準(zhǔn)的框,框內(nèi)具有要素的tif文件
1.以特定點(diǎn)為中心,做一個(gè)1024*1024的框,截取tif圖像
import geopandas as gpd
import rasterio
from rasterio.plot import show
def crop_tif_around_centroid(tif_path, shp_path, output_tif_path, crop_size=1024):
# 讀取shapefile文件以獲取中心點(diǎn)坐標(biāo)
gdf = gpd.read_file(shp_path)
centroid = gdf.iloc[0]['geometry'].centroid
# 讀取tif文件
with rasterio.open(tif_path) as src:
# 獲取tif文件的地理變換參數(shù)
transform = src.transform
# 將中心點(diǎn)的地理坐標(biāo)轉(zhuǎn)換為像素坐標(biāo)
x_center, y_center = rasterio.transform.xy(transform, centroid.x, centroid.y)
# 計(jì)算裁剪窗口的左上角和右下角像素坐標(biāo)
x_min = x_center - (crop_size / 2)
y_min = y_center - (crop_size / 2)
x_max = x_center + (crop_size / 2)
y_max = y_center + (crop_size / 2)
# 確保裁剪窗口不超出tif圖像的邊界
x_min = max(0, min(x_min, src.width - 1))
y_min = max(0, min(y_min, src.height - 1))
x_max = min(src.width, max(x_max, 0))
y_max = min(src.height, max(y_max, 0))
# 創(chuàng)建裁剪窗口
window = ((int(y_min), int(y_max)), (int(x_min), int(x_max)))
# 讀取裁剪窗口內(nèi)的圖像數(shù)據(jù)
out_img = src.read(window=window)
# 更新元數(shù)據(jù)
out_meta = src.meta.copy()
out_meta.update({
"height": y_max - y_min,
"width": x_max - x_min,
"transform": rasterio.transform.from_origin(x_min, y_max, transform[0], transform[4])
})
# 保存裁剪的tif文件
with rasterio.open(output_tif_path, 'w', **out_meta) as dst:
dst.write(out_img)
show(out_img)
# 使用函數(shù)
tif_path = r'E:\jwztestnew\杭州濱江.tif'
shp_path = r'E:\jwztestnew\newshp_5584_centroid.shp'
output_tif_path = r'E:\jwztestnew\杭州濱江_cropped1.tif'
crop_tif_around_centroid(tif_path, shp_path, output_tif_path)
加強(qiáng)版:提取shp文件中各個(gè)多邊形的中心點(diǎn)輸出為shp,然后提取各個(gè)點(diǎn)位以該點(diǎn)位的“TBBM”值為索引,查找文件夾下與之對(duì)應(yīng)的tif,對(duì)相應(yīng)的tif進(jìn)行裁剪,獲得512*512的矩形框
第一段代碼:實(shí)現(xiàn)中心點(diǎn)的提取
import geopandas as gpd
def get_all_centroids_with_attributes(input_shp_path, output_shp_path):
"""
提取輸入shapefile文件中所有有效多邊形的中心點(diǎn),并將“TBBM”列數(shù)據(jù)作為屬性保存到新的shapefile中。
參數(shù):
input_shp_path (str): 輸入shapefile文件的路徑。
output_shp_path (str): 輸出shapefile文件的路徑。
"""
# 讀取shapefile文件
gdf = gpd.read_file(input_shp_path)
# 過(guò)濾掉幾何對(duì)象為None的記錄
gdf_with_geometry = gdf.dropna(subset=['geometry'])
# 計(jì)算所有有效多邊形的中心點(diǎn)
centroids = gdf_with_geometry['geometry'].head(10).apply(lambda x: x.centroid)
# 為了將“TBBM”列數(shù)據(jù)與中心點(diǎn)關(guān)聯(lián),我們需要?jiǎng)?chuàng)建一個(gè)包含中心點(diǎn)和對(duì)應(yīng)“TBBM”值的新字典
centroids_with_attributes = [{"geometry": centroid, "TBBM": gdf_with_geometry.loc[gdf_with_geometry.index, 'TBBM'].iloc[i]} for i, centroid in enumerate(centroids)]
# 創(chuàng)建一個(gè)新的GeoDataFrame來(lái)存儲(chǔ)所有中心點(diǎn)和屬性
centroids_gdf = gpd.GeoDataFrame(centroids_with_attributes, crs=gdf.crs)
# 輸出所有中心點(diǎn)和屬性到新的shapefile
centroids_gdf.to_file(output_shp_path)
# 使用函數(shù)
input_shp_path = r'E:\jwztestnew\newshp_5584(1)\newshp_5584.shp'
output_shp_path = r'E:\jwztestnew\center\newshp_5584_10_centroids_with_bttm.shp'
get_all_centroids_with_attributes(input_shp_path, output_shp_path)
第二段代碼:根據(jù)提取到的中心點(diǎn)做緩沖區(qū)矩形
import geopandas as gpd
import rasterio
import os
from rasterio.windows import Window
from rasterio.transform import Affine
def crop_tif_around_centroid_for_each_tbbm(tif_dir, shp_path, output_dir, crop_size=512):
# 讀取shapefile文件以獲取中心點(diǎn)坐標(biāo)和TBBM列的值
gdf = gpd.read_file(shp_path)
# 創(chuàng)建輸出目錄,如果不存在
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 遍歷shapefile中的每個(gè)點(diǎn)
for index, row in gdf.iterrows():
tbbm = row['TBBM']
centroid = row['geometry'].centroid
print(f'處理TBBM值為 {tbbm} 的點(diǎn) {index + 1}。')
# 在tif目錄下查找名稱與TBBM值一致的tif文件
tif_files = [f for f in os.listdir(tif_dir) if f.startswith(tbbm) and f.endswith('.tif')]
if not tif_files:
print(f'未找到TBBM值為 {tbbm} 的tif文件。')
continue
# 處理每個(gè)找到的tif文件
for tif_file in tif_files:
print(f'開(kāi)始處理文件:{tif_file}。')
tif_path = os.path.join(tif_dir, tif_file)
output_tif_path = os.path.join(output_dir, tif_file)
with rasterio.open(tif_path) as src:
# 獲取tif文件的地理變換參數(shù)
transform = src.transform
# 將中心點(diǎn)的地理坐標(biāo)轉(zhuǎn)換為像素坐標(biāo)
y_center, x_center = rasterio.transform.rowcol(transform, centroid.x, centroid.y)
# 計(jì)算裁剪窗口的左上角和右下角像素坐標(biāo)
x_min = x_center - (crop_size / 2)
y_min = y_center - (crop_size / 2)
x_max = x_center + (crop_size / 2)
y_max = y_center + (crop_size / 2)
# 確保裁剪窗口不超出tif圖像的邊界
x_min = max(0, min(x_min, src.width - 1))
y_min = max(0, min(y_min, src.height - 1))
x_max = min(src.width, max(x_max, 0))
y_max = min(src.height, max(y_max, 0))
width = x_max - x_min
height = y_max - y_min
# 創(chuàng)建裁剪窗口
window = Window(x_min, y_min, width, height)
# 讀取裁剪窗口內(nèi)的圖像數(shù)據(jù)
out_img = src.read(window=window)
# 新的仿射變換系數(shù)
coord_ltx, coord_lty = rasterio.transform.xy(transform, y_min, x_min)
window_affine = Affine(
src.transform[0], # X 像素尺寸
src.transform[1], # X 方向旋轉(zhuǎn)
coord_ltx, # X 偏移量
src.transform[3], # Y 方向旋轉(zhuǎn)
src.transform[4], # Y 像素尺寸
coord_lty # Y 偏移量
)
new_transform = window_affine
# 更新元數(shù)據(jù)
out_meta = src.meta.copy()
out_meta.update({
"height": y_max - y_min,
"width": x_max - x_min,
"transform": new_transform
})
# 保存裁剪的tif文件
with rasterio.open(output_tif_path, 'w', **out_meta) as dst:
dst.write(out_img)
print(f'文件 {tif_file} 處理完成,已保存到 {output_tif_path}。')
# 使用函數(shù)
tif_dir = 'E:\\jwztestnew\\20240329_Sample_8bit'
shp_path = 'E:\\jwztestnew\\center\\newshp_5584_all_centroids_with_bttm.shp'
output_dir = 'Z:\\YuXuening\\ProcessData\\20240410_Sample_8bit_512'
crop_tif_around_centroid_for_each_tbbm(tif_dir, shp_path, output_dir)