Сравнить две папки с изображениями
Находит измененные и отсутствующие файлы, считает разницу пикселей и пишет отчет в JSON.
Что делает скрипт
Скрипт сопоставляет файлы по относительным путям, проверяет размеры и вычисляет среднеквадратичную разницу яркости. Для каждой пары выводится вердикт: совпадает, отличается или имеет другой размер. Ничего не копируется и не удаляется, результаты можно сохранить в JSON.
Быстрый старт
python compare_folders.py --left ./before --right ./after --json diff.json
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python compare_folders.py --left ./before --right ./afterpython compare_folders.py --left ./v1 --right ./v2 --threshold 2.5 --recursive
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
py -m pip install Pillow
python3 -m pip install Pillow
python3 -m pip install Pillow
compare_folders.py
#!/usr/bin/env python3
"""Сравнение изображений в двух папках по относительным путям."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
try:
from PIL import Image, ImageChops, ImageOps, ImageStat
except ImportError:
sys.exit("Нужен Pillow: python3 -m pip install Pillow")
EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff"}
def collect(root: Path, recursive: bool) -> list[Path]:
pattern = "**/*" if recursive else "*"
return sorted(
path for path in root.glob(pattern)
if path.is_file() and path.suffix.lower() in EXTENSIONS
)
def compare_pair(left: Path, right: Path, threshold: float) -> dict:
with Image.open(left) as left_opened, Image.open(right) as right_opened:
left_image = ImageOps.exif_transpose(left_opened).convert("RGB")
right_image = ImageOps.exif_transpose(right_opened).convert("RGB")
if left_image.size != right_image.size:
return {
"status": "size",
"left_size": list(left_image.size),
"right_size": list(right_image.size),
"rms": None,
}
difference = ImageChops.difference(left_image, right_image)
statistic = ImageStat.Stat(difference)
rms = sum(statistic.rms) / 3
box = difference.getbbox()
status = "changed" if rms > threshold else "same"
return {
"status": status,
"rms": round(rms, 4),
"changed_bbox": list(box) if box else None,
}
def main() -> int:
parser = argparse.ArgumentParser(description="Сравнить две папки с изображениями")
parser.add_argument("--left", type=Path, required=True)
parser.add_argument("--right", type=Path, required=True)
parser.add_argument("--threshold", type=float, default=0.0)
parser.add_argument("--recursive", action="store_true")
parser.add_argument("--json", type=Path)
args = parser.parse_args()
left = args.left.expanduser().resolve()
right = args.right.expanduser().resolve()
if not left.exists() or not right.exists():
parser.error("Обе папки должны существовать")
if left.is_file() or right.is_file():
if not (left.is_file() and right.is_file()):
parser.error("Сравнивайте либо два файла, либо две папки")
pairs = [(left, right)]
left_root = left.parent
else:
left_root = left
pairs = []
for path in collect(left, args.recursive):
relative = path.relative_to(left)
candidate = right / relative
if candidate.is_file():
pairs.append((path, candidate))
else:
pairs.append((path, None))
report = []
changed = missing = 0
for left_path, right_path in pairs:
relative = str(left_path.relative_to(left_root))
if right_path is None:
print(f"Нет справа: {relative}")
report.append({"file": relative, "status": "missing"})
missing += 1
continue
try:
result = compare_pair(left_path, right_path, args.threshold)
except Exception as error:
print(f"Ошибка {relative}: {error}")
report.append({"file": relative, "status": "error", "error": str(error)})
continue
result["file"] = relative
report.append(result)
if result["status"] in {"changed", "size"}:
changed += 1
print(f"Отличается: {relative} ({result['status']}, rms={result.get('rms')})")
else:
print(f"Совпадает: {relative}")
print(f"Итог: {len(report)} файлов, изменено {changed}, отсутствует {missing}")
if args.json:
report_path = args.json.expanduser().resolve()
report_path.parent.mkdir(parents=True, exist_ok=True)
report_path.write_text(
json.dumps({"threshold": args.threshold, "files": report}, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
print(f"Отчет сохранен: {args.json}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.