File size: 3,005 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 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 |
from __future__ import annotations
from pathlib import Path
from PIL import Image, ExifTags
import csv
import argparse
def _to_deg(value):
"""Convert EXIF GPS coordinates to float degrees."""
try:
def to_float(x):
try:
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
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
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 extract_split(split_dir: Path) -> Path:
"""Scan a split directory for images and write metadata.csv with
columns: file_name, Latitude, Longitude (as per notebook).
Returns path to the written CSV.
"""
exts = {'.jpg', '.jpeg', '.JPG', '.JPEG'}
rows = []
total = 0
for p in split_dir.rglob('*'):
if p.is_file() and p.suffix in exts:
total += 1
ll = exif_latlon(p)
if ll:
# store path relative to split directory to keep it portable
rel = p.relative_to(split_dir)
rows.append([str(rel).replace('\\\\', '/'), ll[0], ll[1]])
out_csv = split_dir / 'metadata.csv'
with out_csv.open('w', newline='', encoding='utf-8') as f:
w = csv.writer(f)
w.writerow(['file_name', 'Latitude', 'Longitude'])
w.writerows(rows)
print(f"Split: {split_dir}")
print(f"Scanned {total} images; extracted {len(rows)} with GPS.")
print(f"Wrote: {out_csv}")
return out_csv
def main():
ap = argparse.ArgumentParser(description='Extract metadata.csv for a split directory (Route B).')
ap.add_argument('split_dir', type=Path, help='Path to a split directory (e.g., data/train)')
args = ap.parse_args()
if not args.split_dir.exists() or not args.split_dir.is_dir():
raise SystemExit(f"Split directory not found: {args.split_dir}")
extract_split(args.split_dir)
if __name__ == '__main__':
main()
|