CCAiM-CloudsDataset / normalize_names.py
serbekun's picture
Add more photos (now without labels of cloud class.).
2dc9bf5
Raw
History Blame Contribute Delete
2.91 kB
"""Normalize image names in clouds_1/ to sequential numbers.
Files already named as a plain number (e.g. 42.jpg, 105.JPG) are left
untouched. All other images get numbers continuing after the current
maximum, ordered by date: EXIF DateTimeOriginal when present, file
mtime otherwise — so an earlier date always gets a smaller number.
Usage:
python3 normalize_names.py # dry run, prints the plan
python3 normalize_names.py --apply # actually rename
"""
import argparse
import json
import os
import re
import sys
from datetime import datetime
from PIL import Image
FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "clouds_1")
IMAGE_EXTS = {".jpg", ".jpeg", ".png"}
VALID_NAME = re.compile(r"^\d+$")
EXIF_DATETIME_ORIGINAAL = 36867
EXIF_DATETIME_DIGITIZED = 36868
EXIF_DATETIME = 306
def get_date(path):
"""EXIF capture date if available, otherwise file mtime."""
try:
with Image.open(path) as img:
exif = img.getexif()
raw = (
exif.get_ifd(0x8769).get(EXIF_DATETIME_ORIGINAAL)
or exif.get_ifd(0x8769).get(EXIF_DATETIME_DIGITIZED)
or exif.get(EXIF_DATETIME)
)
if raw:
return datetime.strptime(str(raw), "%Y:%m:%d %H:%M:%S")
except Exception:
pass
return datetime.fromtimestamp(os.path.getmtime(path))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--apply", action="store_true", help="perform the renames")
args = parser.parse_args()
max_num = -1
to_rename = []
for name in sorted(os.listdir(FOLDER)):
stem, ext = os.path.splitext(name)
if ext.lower() not in IMAGE_EXTS:
continue
if VALID_NAME.match(stem):
max_num = max(max_num, int(stem))
else:
path = os.path.join(FOLDER, name)
to_rename.append((get_date(path), name, ext))
if not to_rename:
print("Nothing to rename: all image names are already numeric.")
return
to_rename.sort() # by date, then name for stable ties
mapping = {}
next_num = max_num + 1
for date, name, ext in to_rename:
new_name = f"{next_num}{ext}"
mapping[name] = new_name
print(f"{date} {name:30s} -> {new_name}")
next_num += 1
if not args.apply:
print(f"\nDry run: {len(mapping)} files would be renamed "
f"({max_num + 1}..{next_num - 1}). Re-run with --apply.")
return
for old, new in mapping.items():
os.rename(os.path.join(FOLDER, old), os.path.join(FOLDER, new))
map_path = os.path.join(FOLDER, "rename_map.json")
with open(map_path, "w") as f:
json.dump(mapping, f, indent=2, ensure_ascii=False)
print(f"\nRenamed {len(mapping)} files; mapping saved to {map_path}")
if __name__ == "__main__":
sys.exit(main())