Datasets:
File size: 4,271 Bytes
0a7933d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | '''
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}")
|