# Tactiverge Academy — companion code for "Images as arrays of numbers"
# Lesson: https://tactiverge.win/academy/computational-engineering/introduction-to-computer-vision/images-as-arrays/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
image = [
    [ 10,  10,  10,  10,  10],
    [ 10, 200, 200, 200,  10],
    [ 10, 200, 255, 200,  10],
    [ 10, 200, 200, 200,  10],
    [ 10,  10,  10,  10,  10],
]

height = len(image)        # number of rows
width = len(image[0])      # number of columns
print(f"{width} x {height} pixels")
print(image[2][2])         # row 2, column 2: the centre
print(image[0][4])         # top-right corner


# ── Example 2 ────────────────────────────────────────
def show(img):
    shades = ".:-=+*#%@"            # dark to bright
    for row in img:
        line = ""
        for value in row:
            line += shades[value * (len(shades) - 1) // 255] * 2
        print(line)

show(image)

total = 0
for row in image:
    total += sum(row)
pixels = len(image) * len(image[0])
print(f"Mean brightness: {total / pixels:.1f}")

negative = [[255 - v for v in row] for row in image]
print(negative[2])


# ── Example 3 ────────────────────────────────────────
orange = (255, 140, 0)    # (red, green, blue)

def to_grey(rgb):
    r, g, b = rgb
    return round(0.299 * r + 0.587 * g + 0.114 * b)

print(to_grey(orange))
print(to_grey((255, 0, 0)), to_grey((0, 255, 0)), to_grey((0, 0, 255)))

width, height, channels = 640, 480, 3
size_bytes = width * height * channels
print(f"{size_bytes} bytes per frame")
print(f"{size_bytes * 30 / 1e6:.1f} MB per second at 30 frames per second")


# ── Example 4 ────────────────────────────────────────
image = [
    [ 10,  20,  30,  40],
    [ 50,  60,  70,  80],
    [ 90, 100, 110, 120],
    [130, 140, 150, 160],
]

def downsample(img):
    """Halve the resolution by averaging each 2 x 2 block."""
    small = []
    for r in range(0, len(img), 2):
        row = []
        for c in range(0, len(img[0]), 2):
            block = img[r][c] + img[r][c + 1] + img[r + 1][c] + img[r + 1][c + 1]
            row.append(block // 4)
        small.append(row)
    return small

print(downsample(image))
