File size: 2,755 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
'''
Convert shapefile annotations to a format suitable for training a deep learning model. 

'''

#==============================================================================
#%% IMPORTS
#==============================================================================
from pathlib import Path
import geopandas as gpd
from shapely.geometry import Point
from shapely.geometry import box
import rasterio
import json
import numpy as np
import cv2
from tqdm.auto import tqdm
#==============================================================================
#%% CONFIGURATION
#==============================================================================

KEY_ID = "BRA_SP"
SHAPEFILE_PATH = Path('/home/sabrina/Documents/Tese/00_Dados/01_Keypoints_SHP/pontos_liberdadefinal.shp')
IMG_DIR        = Path(f'/home/sabrina/Documents/Tese/05_Dataset/MatchGeo-DEM-v1/data/{KEY_ID}/tiles')
ANNO_DIR       = Path(f'/home/sabrina/Documents/Tese/05_Dataset/MatchGeo-DEM-v1/data/{KEY_ID}/annotation')

ANNO_DIR.mkdir(exist_ok=True)

#==============================================================================
#%% CONVERT SHAPEFILE TO JSON ANNOTATIONS
#==============================================================================
gdf = gpd.read_file(SHAPEFILE_PATH)

img_files = sorted(IMG_DIR.glob('*.tif'))
print(f"Found {len(img_files)} images to process.")

for img_file in tqdm(img_files, desc="Processing images"):

    with rasterio.open(img_file) as src:
        profile = src.profile
        transform = src.transform

        # Check if there are point inf the gdf inside the image bounds
        img_bounds = rasterio.transform.array_bounds(profile['height'], profile['width'], transform)
        img_poly = box(*img_bounds)  
        if not gdf.intersects(img_poly).any():
            print(f"No keypoints found in {img_file.stem}, skipping.")
            continue


        # Intersect the GeoDataFrame with the image bounds to get only relevant keypoints
        gdf_img = gdf[gdf.intersects(img_poly)]
        # Convert to pixel coordinates
        keypoints = []
        for idx, row in gdf_img.iterrows():
            geom = row.geometry
            if isinstance(geom, Point):
                x, y = geom.x, geom.y
                # Convert to pixel coordinates
                col, row = ~transform * (x, y)
                keypoints.append((int(col)/profile['width'], int(row)/profile['height']))  # Normalize to [0, 1]
            

        # Create annotation dictionary
        anno = {
            "image": img_file.name,
            "keypoints": keypoints
        }
        # Save annotation as JSON
        anno_file = ANNO_DIR / f"{img_file.stem}.json"
        with open(anno_file, 'w') as f:
            json.dump(anno, f, indent=4)

# %%