#!/usr/bin/env python3
"""Sharpness of one rectangle of a picture: variance of the Laplacian of its grayscale.
Usage: python3 region-sharpness.py <image> <x> <y> <width> <height>
Higher = more fine detail, 0 = perfectly flat. Compare the SAME rectangle before and after blurring.
Needs: pip install pillow numpy"""
import os
import sys

try:
    import numpy as np
    from PIL import Image
except ImportError:
    sys.exit("error: needs Pillow and numpy (pip install pillow numpy)")


def fail(msg):
    sys.exit("error: " + msg)


if len(sys.argv) != 6:
    fail("usage: region-sharpness.py <image> <x> <y> <width> <height>")
path = sys.argv[1]
if not os.path.isfile(path):
    fail("file not found: " + path)
if os.path.getsize(path) == 0:
    fail("file is empty: " + path)
try:
    x, y, w, h = (int(v) for v in sys.argv[2:6])
except ValueError:
    fail("x, y, width and height must be whole numbers of pixels")
try:
    img = Image.open(path)
    img.load()
except Exception:
    fail("not a picture Pillow can read: " + path)
if w < 3 or h < 3:
    fail("the rectangle must be at least 3 x 3 pixels")
if x < 0 or y < 0 or x + w > img.width or y + h > img.height:
    fail("the rectangle leaves the picture (%d x %d px)" % (img.width, img.height))

g = np.asarray(img.convert("RGB"), dtype=np.float64)[y:y + h, x:x + w]
g = g @ np.array([0.299, 0.587, 0.114])
lap = g[:-2, 1:-1] + g[2:, 1:-1] + g[1:-1, :-2] + g[1:-1, 2:] - 4 * g[1:-1, 1:-1]
print("%s  rect %d,%d %dx%d  sharpness %.2f" % (os.path.basename(path), x, y, w, h, lap.var()))
