#!/usr/bin/env python3 """Поиск изображений, похожих на заданный образец.""" from __future__ import annotations import argparse import json import sys from pathlib import Path try: from PIL import Image, ImageOps except ImportError: sys.exit("Нужен Pillow: python3 -m pip install Pillow") EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff"} def dhash(path: Path, size: int = 8) -> int: with Image.open(path) as opened: image = ImageOps.exif_transpose(opened).convert("L") image = image.resize((size + 1, size), Image.Resampling.LANCZOS) pixels = image.tobytes() value = 0 for row in range(size): for column in range(size): left = pixels[row * (size + 1) + column] right = pixels[row * (size + 1) + column + 1] value = (value << 1) | (1 if left > right else 0) return value 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 main() -> int: parser = argparse.ArgumentParser(description="Найти изображения, похожие на образец") parser.add_argument("--reference", type=Path, required=True) parser.add_argument("--dir", type=Path, required=True) parser.add_argument("--threshold", type=int, default=10) parser.add_argument("--top", type=int, default=20) parser.add_argument("--recursive", action="store_true") parser.add_argument("--json", type=Path) args = parser.parse_args() if not 0 <= args.threshold <= 64: parser.error("--threshold должен быть от 0 до 64") if args.top < 1: parser.error("--top должен быть больше нуля") reference = args.reference.expanduser().resolve() root = args.dir.expanduser().resolve() if not reference.is_file(): parser.error(f"Образец не найден: {reference}") if not root.is_dir(): parser.error(f"Папка не найдена: {root}") try: reference_hash = dhash(reference) except Exception as error: print(f"Не удалось прочитать образец: {error}") return 1 matches = [] for path in collect(root, args.recursive): if path.resolve() == reference: continue try: distance = (reference_hash ^ dhash(path)).bit_count() except Exception as error: print(f"Пропуск {path}: {error}") continue if distance <= args.threshold: matches.append((distance, path)) matches.sort(key=lambda item: (item[0], str(item[1]))) matches = matches[:args.top] if not matches: print("Похожие изображения не найдены.") for distance, path in matches: print(f"{distance:2d} {path}") print(f"Найдено: {len(matches)}") if args.json: payload = [{"distance": distance, "file": str(path)} for distance, path in matches] report_path = args.json.expanduser().resolve() report_path.parent.mkdir(parents=True, exist_ok=True) report_path.write_text( json.dumps( {"reference": str(reference), "threshold": args.threshold, "matches": payload}, ensure_ascii=False, indent=2, ) + "\n", encoding="utf-8", ) print(f"Отчет сохранен: {args.json}") return 0 if __name__ == "__main__": raise SystemExit(main())