Images as arrays of pixels
To a computer, a digital image is a grid of numbers. Each grid cell is a pixel. A grayscale image has one number per pixel, usually an 8-bit integer from 0 (black) to 255 (white). A color image has several channels per pixel, most often red, green, and blue, so its shape is height × width × 3. In Python, a small image is naturally a list of rows, and image[row][col] reads one pixel. The first index is the row, which is the vertical position y, and the second is the column, the horizontal position x, so coordinates are often written (row, col) rather than (x, y).
Python
image = [
[0, 50, 100],
[150, 200, 250],
]
def to_gray(pixel):
red, green, blue = pixel
return round(0.299 * red + 0.587 * green + 0.114 * blue)
def brighten(img, amount):
return [[min(255, max(0, value + amount)) for value in row] for row in img]
def normalize(img):
return [[value / 255 for value in row] for row in img]
print(len(image), len(image[0]))
print(to_gray((200, 100, 50)), to_gray((255, 255, 255)))
print(brighten(image, 100))
print([[round(value, 2) for value in row] for row in normalize(image)])
print(image[1][2])