OCRで画像リネームを自動化してみる



カードゲームのツール開発で、当然カード画像をたくさん作ることになる。 その際に角R透過ツールという、画像の角を丸めてくれる最高のツールがあるのだが、画像の出力が "trimmed-image", "trimmed-image(1)" ... となりそれをリネームしなくてはいけない。 100枚分ぐらいリネームをやってみたが、人間がやる作業ではなさすぎた。
## たすけてOCR OCR で文字を読み取って、自動でリネームさせてみることにした。
なんと Python 触るのがほぼ初めてだったので、Python すげ〜となった。
### たすけてclaude Python 右も左も猫も杓子もわからないので claude にたすけてもらう。
easy OCR いれる ``` pip install easyocr --break-system-packages ```
コード ``` from PIL import Image, ImageEnhance, ImageOps import easyocr, re, sys from pathlib import Path reader = easyocr.Reader(['en']) def reconstruct_id(text): text = re.sub(r'[^A-Z0-9]', '', text.upper()) text = text.replace('T', '1') m = re.search(r'(WX(?:Di|K|EX|A))([A-Z]+\d+?)(\d{3})', text) if m: return f"{m.group(1)}-{m.group(2)}-{m.group(3)}" m = re.search(r'(WX\d{2})([A-Z]+\d+?)(\d{3})', text) if m: return f"{m.group(1)}-{m.group(2)}-{m.group(3)}" return None def get_card_id(image_path, debug=False): img = Image.open(image_path) img = img.convert('RGB') w, h = img.size if w > h: crop = img.crop((0, h * 0.94, w * 0.45, h)) else: crop = img.crop((0, h * 0.96, w * 0.45, h)) crop = crop.resize((crop.width * 4, crop.height * 4), Image.LANCZOS) if debug: script_dir = Path(__file__).parent crop.save(script_dir / "debug_crop.png") import numpy as np results = reader.readtext(np.array(crop), allowlist='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-') text = ' '.join([r[1] for r in results]) if debug: print(f"OCRの生テキスト: [{text}]") text = text.replace('T', '1') m = re.search(r'WX[\w]+-[\w]+-\d{3}', text) if m: return m.group() return reconstruct_id(text) debug_mode = '--debug' in sys.argv args = [a for a in sys.argv[1:] if not a.startswith('--')] folder = Path(args[0]) if args else Path(".") if folder.is_file(): card_id = get_card_id(folder, debug=debug_mode) print(f"{'✅' if card_id else '❌'} {folder.name} → {card_id or '読めなかった'}") else: for img_path in folder.glob("*"): if img_path.suffix.lower() not in ['.jpg', '.jpeg', '.png']: continue card_id = get_card_id(img_path, debug=debug_mode) if card_id: new_path = img_path.parent / f"{card_id}{img_path.suffix}" img_path.rename(new_path) print(f"✅ {img_path.name} → {card_id}") else: print(f"❌ 読めなかった: {img_path.name}") ```
カード画像の ID が書いてある部分を切り出し、モノクロ等に補正して OCR に読ませる。 余計な文字列を読み取ってしまうこともあるので、ID の形式に補正してリネーム。
### やってみる claude に頼んで引数からカッコよく使えるようにしてもらった。 ``` ❯ python3 '/home/shiroka/画像/wixoss/for-wixdex-auto-rename.py' '/home/shiroka/画像/wixoss/WXDi-CP02/trimmed/' ```
こんな感じでリネームしてほしいフォルダを引数にして渡す。かっこいい〜〜 精度がかなりよく、たまにあるイカれた位置に ID が書いてあるもの以外は基本的に読める。 ただ、ゼロとオー、2 と Z など似ている文字を誤爆してしまうが、これは OCR の限界点な気もするので、Python 側でうまいこと補正してあげたい。