matchgeodem / scripts /crop_tiles.py
paeslemesa's picture
Updated statcs/ splis/ and scrips/
0a7933d verified
Raw History Blame Contribute Delete
4.27 kB
'''
Crop Dataset to 333x333 pixels for faster processing and testing.
This script reads the original DEM images, crops them to the specified size, and saves the cropped versions in a new directory.
The annotations are also updated accordingly to reflect the new image dimensions.
'''
#------------------------------------------------------------------------
#%% IMPORTS
from pathlib import Path
import math
import rasterio
from rasterio.windows import Window
from shapely.geometry import box
import geopandas as gpd
import numpy as np
from tqdm.auto import tqdm
#------------------------------------------------------------------------
#%% CONFIGURATION
AREAS = {'ATA_MV', 'BRA_SP', 'CHN_WS', 'ESP_EH', 'FIN_LM', 'GER_BN', 'IDN_SV', 'KAZ_AC', 'KSA_WA', 'NAM_HF', 'NZL_KP', 'PHL_TA', 'USA_GC'}
#AREAS = {'ATA_MV'}
WIDTH = 256
HEIGHT = 256
#------------------------------------------------------------------------
for KEY_ID in tqdm(AREAS):
IMG_DIR = Path(f'/home/sabrina/Documents/Tese/05_Dataset/MatchGeo-DEM-v1/data/{KEY_ID}')
CROPPED_IMG_DIR = Path(IMG_DIR, 'tiles')
CROPPED_IMG_DIR.mkdir(exist_ok=True)
# CROP IMAGES
img_files = sorted(IMG_DIR.glob(f'{KEY_ID}.tif'), key=lambda x: x.stem)
dicto_records = {
'tile_id' : [],
'row_idx' : [],
'col_idx' : [],
'geometry': []
}
for img_file in tqdm(img_files, desc="Cropping images"):
# Create a folder for each City in the cropped directory
city = img_file.parent.name
with rasterio.open(img_file) as src:
crs = src.crs
img = src.read(1)
nodata = src.nodata if src.nodata is not None else -9999
n_rows = math.ceil(src.height / HEIGHT)
n_cols = math.ceil(src.width / WIDTH)
padded_w = n_cols * WIDTH
padded_h = n_rows * HEIGHT
pad_right = padded_w - src.width
pad_bottom = padded_h - src.height
if pad_right > 0 or pad_bottom > 0:
img = np.pad(
img,
((0, pad_bottom), (0, pad_right)),
mode='constant',
constant_values=nodata
)
#----------------------------------------------
for row in range(n_rows):
for col in range(n_cols):
row_off = row * HEIGHT
col_off = col * WIDTH
tile = img[row_off:row_off + HEIGHT, col_off:col_off + WIDTH]
# Skip completely uniform (null) tiles
if np.unique(tile).size == 1:
print("Skipping null tile")
continue
window = Window(
col_off=col_off,
row_off=row_off,
width=WIDTH,
height=HEIGHT
)
transform = src.window_transform(window)
cropped_image = src.read(1, window=window)
left, bottom, right, top = src.window_bounds(window)
profile = src.profile.copy()
profile.update({
"height": HEIGHT,
"width": WIDTH,
"transform": transform,
"nodata": nodata # ensure nodata is set correctly
})
out_file = Path(CROPPED_IMG_DIR, KEY_ID + f'_{row+1:03d}_{col+1:03d}.tif')
with rasterio.open(out_file, 'w', **profile) as dst:
dst.write(cropped_image, 1)
dicto_records['tile_id'].append(f"{img_file.stem}_{row+1:03d}_{col+1:03d}")
dicto_records['row_idx'].append(row+1)
dicto_records['col_idx'].append(col+1)
dicto_records['geometry'].append(box(left, bottom, right, top))
print('Saving vector..')
TILES_FILE = Path(IMG_DIR, KEY_ID + '_tiles.geojson')
gdf = gpd.GeoDataFrame(dicto_records, crs = crs, geometry='geometry')
gdf.to_file(TILES_FILE, driver='GEOJSON', mode='a')
print(f"Saved files to {CROPPED_IMG_DIR}")