File size: 3,658 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
import rasterio
from pathlib import Path
import numpy as np

#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'}

path = Path("/home/sabrina/Documents/Tese/05_Dataset/MatchGeo-DEM-v1/data")



print("=" * 70)
print("MatchGeo-DEM NoData Fixer (Fixed)")
print("=" * 70)

for location in sorted(areas):
    loc_path = Path(path, f"{location}/{location}.tif")

    if not loc_path.exists():
        print(f"\n⚠️  {location}: File not found — skipping")
        continue

    with rasterio.open(loc_path) as src:
        nodata = src.nodata

        # Check current state
        profile = src.profile
        is_bigtiff = profile.get('bigtiff', 'NO')
        is_tiled = profile.get('tiled', False)
        compress = profile.get('compress', 'NONE')
        block_x = profile.get('blockxsize', 0)
        block_y = profile.get('blockysize', 0)

        needs_fix = (nodata != -9999.0 or is_bigtiff != 'YES' or 
                     not is_tiled or compress != 'deflate')

        if not needs_fix:
            print(f"\n✅ {location}: Already perfect (NoData={nodata}, BigTIFF={is_bigtiff}, Tiled={is_tiled}, Deflate={compress})")
            continue

        print(f"\n🔧 {location}: Fixing...")
        print(f"   Current: NoData={nodata}, BigTIFF={is_bigtiff}, Tiled={is_tiled}, Compress={compress}")

        # Read the data
        band = src.read(1)

        # Handle existing NoData values
        if nodata is not None and nodata != -9999.0:
            band[band == nodata] = -9999
            print(f"   Replaced old NoData ({nodata}) with -9999")

        # Handle NaN values if present
        if np.isnan(band).any():
            nan_count = np.isnan(band).sum()
            band = np.nan_to_num(band, nan=-9999)
            print(f"   Replaced {nan_count} NaN values with -9999")

        # Build profile from scratch to avoid conflicts
        # Use GTiff driver with explicit options
        kwargs = {
            'driver': 'GTiff',
            'height': band.shape[0],
            'width': band.shape[1],
            'count': 1,
            'dtype': 'float32',
            'crs': src.crs,
            'transform': src.transform,
            'nodata': -9999.0,
            'tiled': True,
            'blockxsize': 256,
            'blockysize': 256,
            'compress': 'deflate',
            'predictor': 2,
            'zlevel': 6,
            'bigtiff': 'YES',
            'interleave': 'band',
        }

        # Write the corrected file
        output_path = loc_path.with_suffix('.fixed.tif')

        try:
            with rasterio.open(output_path, 'w', **kwargs) as dst:
                dst.write(band, 1)

            # Verify
            with rasterio.open(output_path) as dst:
                v_nodata = dst.nodata
                v_bigtiff = dst.profile.get('bigtiff', 'NO')
                v_tiled = dst.profile.get('tiled', False)
                v_compress = dst.profile.get('compress', 'NONE')

                print(f"   ✅ Fixed file: {output_path}")
                print(f"   ✅ NoData: {v_nodata}")
                print(f"   ✅ BigTIFF: {v_bigtiff}")
                print(f"   ✅ Tiled: {v_tiled}")
                print(f"   ✅ Compression: {v_compress}")

        except Exception as e:
            print(f"   ❌ ERROR writing {location}: {e}")
            print(f"   💡 Try deleting {output_path} if it exists and re-run")
            if output_path.exists():
                output_path.unlink()

print("\n" + "=" * 70)
print("Done! Check .fixed.tif files.")
print("=" * 70)