Выровнять уровни и контраст
Растягивает гистограмму и убирает тусклость снимков, сохраняя копии в отдельной папке.
Что делает скрипт
Скрипт применяет autocontrast с настраиваемым отсечением крайних пикселей и по желанию дополнительное выравнивание гистограммы. Альфа-канал PNG и WebP не страдает. Это быстрый способ привести серию фото к более живому виду без ручной цветокоррекции.
Быстрый старт
python auto_contrast.py --dir ./photos --out ./contrast --cutoff 0.5
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python auto_contrast.py --dir ./photos --out ./contrastpython auto_contrast.py --dir ./photos --out ./contrast --cutoff 2 --equalize --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
auto_contrast.py
#!/usr/bin/env python3
"""Автоматическая коррекция уровней и контраста."""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
try:
from PIL import Image, ImageOps
except ImportError:
sys.exit("Нужен Pillow: python3 -m pip install Pillow")
FORMATS = {
".jpg": "JPEG",
".jpeg": "JPEG",
".png": "PNG",
".webp": "WEBP",
".tif": "TIFF",
".tiff": "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 FORMATS
)
def correct(image: Image.Image, cutoff: float, equalize: bool) -> Image.Image:
if image.mode in ("RGBA", "LA") or (image.mode == "P" and "transparency" in image.info):
rgba = image.convert("RGBA")
alpha = rgba.getchannel("A")
rgb = ImageOps.autocontrast(rgba.convert("RGB"), cutoff=cutoff)
if equalize:
rgb = ImageOps.equalize(rgb)
rgb.putalpha(alpha)
return rgb
if image.mode == "L":
result = ImageOps.autocontrast(image, cutoff=cutoff)
return ImageOps.equalize(result) if equalize else result
if image.mode != "RGB":
image = image.convert("RGB")
result = ImageOps.autocontrast(image, cutoff=cutoff)
return ImageOps.equalize(result) if equalize else result
def main() -> int:
parser = argparse.ArgumentParser(description="Выровнять уровни и контраст")
parser.add_argument("--dir", type=Path, required=True)
parser.add_argument("--out", type=Path, required=True)
parser.add_argument("--cutoff", type=float, default=0.5)
parser.add_argument("--equalize", action="store_true")
parser.add_argument("--recursive", action="store_true")
parser.add_argument("--overwrite", action="store_true")
args = parser.parse_args()
if not 0 <= args.cutoff < 50:
parser.error("--cutoff должен быть от 0 до 49.9")
root = args.dir.expanduser().resolve()
if not root.is_dir():
parser.error(f"Папка не найдена: {root}")
out_dir = args.out.expanduser().resolve()
out_dir.mkdir(parents=True, exist_ok=True)
files = collect(root, args.recursive)
if not files:
print("Изображения не найдены.")
return 0
done = skipped = failed = 0
for path in files:
target = out_dir / path.name
if target.exists() and not args.overwrite:
skipped += 1
continue
try:
with Image.open(path) as opened:
image = ImageOps.exif_transpose(opened)
result = correct(image, args.cutoff, args.equalize)
fmt = FORMATS[path.suffix.lower()]
if fmt == "JPEG":
if result.mode != "RGB":
result = result.convert("RGB")
result.save(
target, format="JPEG", quality=92, optimize=True, progressive=True
)
elif fmt == "PNG":
result.save(target, format="PNG", optimize=True)
elif fmt == "WEBP":
result.save(target, format="WEBP", quality=90, method=6)
else:
if result.mode not in ("RGB", "RGBA", "L"):
result = result.convert("RGB")
result.save(target, format="TIFF", compression="tiff_deflate")
except Exception as error:
print(f"Ошибка {path}: {error}")
failed += 1
continue
done += 1
print(f"Готово: {path.name}")
print(f"Итог: {done} готово, {skipped} пропущено, {failed} ошибок")
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.