"""Image basics: I/O, indexing, kernels, convolution, and basic filters.

Companion code for the CS 4288 "Image Basics" tutorial.
Requires: pip install numpy pillow
Usage:    python3 image_basics.py astronaut.png
"""
import sys

import numpy as np
from PIL import Image


def load_gray(path):
    """Read an image file and return a 2-D float32 array in [0, 255]."""
    return np.asarray(Image.open(path).convert("L"), dtype=np.float32)


def save(arr, path):
    """Clip an array to [0, 255] and write it as an 8-bit image."""
    Image.fromarray(np.clip(arr, 0, 255).astype(np.uint8)).save(path)


def correlate_slow(im, k):
    """Apply kernel k to every pixel of im, one pixel at a time."""
    a, b = k.shape[0] // 2, k.shape[1] // 2
    padded = np.pad(im, ((a, a), (b, b)), mode="edge")
    out = np.zeros_like(im)
    for i in range(im.shape[0]):
        for j in range(im.shape[1]):
            total = 0.0
            for u in range(-a, a + 1):
                for v in range(-b, b + 1):
                    total += k[u + a, v + b] * padded[i + a + u, j + b + v]
            out[i, j] = total
    return out


def correlate(im, k):
    """Same result as correlate_slow, but loops over the kernel, not the image."""
    a, b = k.shape[0] // 2, k.shape[1] // 2
    padded = np.pad(im, ((a, a), (b, b)), mode="edge")
    height, width = im.shape
    out = np.zeros_like(im)
    for u in range(-a, a + 1):
        for v in range(-b, b + 1):
            out += k[u + a, v + b] * padded[a + u:a + u + height,
                                            b + v:b + v + width]
    return out


def gaussian_kernel(size, sigma):
    """Return a size x size Gaussian kernel whose entries sum to 1."""
    r = size // 2
    x = np.arange(-r, r + 1, dtype=np.float32)
    g = np.exp(-x**2 / (2 * sigma**2))
    k = np.outer(g, g)
    return k / k.sum()


BOX = np.ones((5, 5), dtype=np.float32) / 25

SHARPEN = np.array([[0, -1, 0],
                    [-1, 5, -1],
                    [0, -1, 0]], dtype=np.float32)

SOBEL_X = np.array([[-1, 0, 1],
                    [-2, 0, 2],
                    [-1, 0, 1]], dtype=np.float32)
SOBEL_Y = SOBEL_X.T

LAPLACIAN = np.array([[0, 1, 0],
                      [1, -4, 1],
                      [0, 1, 0]], dtype=np.float32)


def adjust(im, contrast=1.0, brightness=0.0, gamma=1.0):
    """Scale contrast around mid-gray, add brightness, then apply gamma."""
    out = np.clip(contrast * (im - 128) + 128 + brightness, 0, 255)
    return 255 * (out / 255) ** gamma


def rotate_nearest(im, degrees):
    """Rotate counterclockwise about the center, by inverse mapping:
    for each output pixel, look up the input pixel it came from."""
    height, width = im.shape
    cy, cx = (height - 1) / 2, (width - 1) / 2
    theta = np.deg2rad(degrees)
    rows, cols = np.indices(im.shape)
    y, x = rows - cy, cols - cx                   # output, relative to center
    src_x = np.cos(theta) * x - np.sin(theta) * y + cx
    src_y = np.sin(theta) * x + np.cos(theta) * y + cy
    src_i, src_j = np.round(src_y).astype(int), np.round(src_x).astype(int)
    inside = (src_i >= 0) & (src_i < height) & (src_j >= 0) & (src_j < width)
    out = np.zeros_like(im)                       # black where nothing maps
    out[inside] = im[src_i[inside], src_j[inside]]
    return out


def perspective_coeffs(dst, src):
    """Solve for the 8 coefficients (a..h) of the perspective map taking
    each output point (x, y) in dst to its input point (X, Y) in src:
    X = (a x + b y + c) / (g x + h y + 1),  Y = (d x + e y + f) / (g x + h y + 1)."""
    rows, rhs = [], []
    for (x, y), (big_x, big_y) in zip(dst, src):
        rows.append([x, y, 1, 0, 0, 0, -big_x * x, -big_x * y])
        rows.append([0, 0, 0, x, y, 1, -big_y * x, -big_y * y])
        rhs += [big_x, big_y]
    return np.linalg.solve(np.array(rows, dtype=float), np.array(rhs, dtype=float))


def main():
    """Run every filter on one image and save the results."""
    im = load_gray(sys.argv[1] if len(sys.argv) > 1 else "astronaut.png")
    print("shape:", im.shape, "dtype:", im.dtype)

    # The fast and slow versions agree (checked on a small crop for speed).
    crop = im[:40, :40]
    assert np.allclose(correlate(crop, SOBEL_X), correlate_slow(crop, SOBEL_X))

    save(im, "gray.png")
    save(correlate(im, BOX), "box.png")
    save(correlate(im, gaussian_kernel(9, 2.0)), "gaussian.png")
    save(correlate(im, SHARPEN), "sharpen.png")

    gx = correlate(im, SOBEL_X)
    gy = correlate(im, SOBEL_Y)
    magnitude = np.hypot(gx, gy)
    save(128 + gx / 8, "sobel_x.png")  # gray = 0, light = positive
    save(128 + gy / 8, "sobel_y.png")
    save(255 * magnitude / np.percentile(magnitude, 99), "sobel_mag.png")

    save(128 + 2 * correlate(im, LAPLACIAN), "laplacian.png")
    smoothed = correlate(im, gaussian_kernel(9, 2.0))
    save(128 + 8 * correlate(smoothed, LAPLACIAN), "log.png")
    print("wrote gray, box, gaussian, sharpen, sobel_x, sobel_y, sobel_mag,"
          " laplacian, log")

    # Resizing: shrink 4x by dropping pixels, then the right way.
    pil = Image.fromarray(im.astype(np.uint8))
    small_slice = Image.fromarray(im[::4, ::4].astype(np.uint8))
    small_lanczos = pil.resize((128, 128), Image.Resampling.LANCZOS)
    for name, small in [("small_slice", small_slice), ("small_lanczos", small_lanczos)]:
        small.save(f"{name}.png")
        # Enlarge one region 6x, without smoothing, to see the pixels.
        small.crop((0, 0, 48, 48)).resize((288, 288), Image.Resampling.NEAREST).save(
            f"{name}_zoom.png")

    # Transformations.
    save(np.fliplr(im), "flip.png")
    save(rotate_nearest(im, 30), "rotate_nearest.png")
    pil.rotate(30, resample=Image.Resampling.BILINEAR).save("rotate_pil.png")
    save(adjust(im, brightness=60), "brighter.png")
    save(adjust(im, contrast=1.6), "contrast.png")
    save(adjust(im, gamma=0.5), "gamma.png")
    corners = [(0, 0), (511, 0), (511, 511), (0, 511)]          # (x, y)
    tilted = [(80, 60), (511, 0), (511, 511), (80, 451)]
    coeffs = perspective_coeffs(tilted, corners)
    pil.transform(pil.size, Image.Transform.PERSPECTIVE, coeffs,
                  Image.Resampling.BILINEAR).save("perspective.png")
    print("wrote small_slice, small_lanczos, flip, rotate_nearest, rotate_pil,"
          " brighter, contrast, gamma, perspective")


if __name__ == "__main__":
    main()
