File size: 2,823 Bytes
d2efaca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from pathlib import Path
from PIL import Image, ExifTags
import csv
import sys
def _to_deg(value):
    """Convert EXIF GPS coordinates to float degrees.

    Supports either tuple-of-(num,den) or tuple-of-floats.

    """
    try:
        def to_float(x):
            try:
                # PIL may provide rational as tuple (num, den)
                if isinstance(x, tuple) and len(x) == 2:
                    return x[0] / x[1]
            except Exception:
                pass
            return float(x)
        d = to_float(value[0])
        m = to_float(value[1])
        s = to_float(value[2])
        return d + (m / 60.0) + (s / 3600.0)
    except Exception:
        return None
def exif_latlon(img_path: Path):
    """Read (lat, lon) from image EXIF. Returns tuple or None if missing."""
    try:
        with Image.open(img_path) as img:
            exif = img._getexif() or {}
    except Exception:
        return None
    if not exif:
        return None
    # Map main EXIF tags
    exif_dict = {ExifTags.TAGS.get(k, k): v for k, v in exif.items()}
    gps_tag = exif_dict.get('GPSInfo')
    if not gps_tag:
        return None
    # Map GPS sub-tags
    gps = {ExifTags.GPSTAGS.get(k, k): v for k, v in gps_tag.items()}
    lat_raw = gps.get('GPSLatitude')
    lon_raw = gps.get('GPSLongitude')
    if lat_raw is None or lon_raw is None:
        return None
    lat = _to_deg(lat_raw)
    lon = _to_deg(lon_raw)
    if lat is None or lon is None:
        return None
    if gps.get('GPSLatitudeRef', 'N') in ('S', b'S'):
        lat = -lat
    if gps.get('GPSLongitudeRef', 'E') in ('W', b'W'):
        lon = -lon
    return lat, lon
def walk_and_dump(img_root: Path, out_csv: Path):
    exts = {'.jpg', '.jpeg', '.png', '.JPG', '.JPEG', '.PNG'}
    rows = []
    total = 0
    for p in img_root.rglob('*'):
        if p.suffix in exts and p.is_file():
            total += 1
            ll = exif_latlon(p)
            if ll:
                rows.append([str(p), ll[0], ll[1]])
    out_csv.parent.mkdir(parents=True, exist_ok=True)
    with out_csv.open('w', newline='', encoding='utf-8') as f:
        w = csv.writer(f)
        w.writerow(['path', 'lat', 'lon'])
        w.writerows(rows)
    print(f"Scanned {total} images, extracted {len(rows)} with GPS.")
    print(f"Wrote: {out_csv}")
def main(argv=None):
    argv = argv or sys.argv[1:]
    if len(argv) == 0:
        print("Usage: python scripts/exif_to_csv.py <img_root> [out_csv]")
        print("Example: python scripts/exif_to_csv.py data/raw_images data/labels.csv")
        sys.exit(1)
    img_root = Path(argv[0])
    out_csv = Path(argv[1]) if len(argv) > 1 else Path('data/labels.csv')
    walk_and_dump(img_root, out_csv)
if __name__ == '__main__':
    main()