def normalize_brightness(img: Image) -> Image:
"""
Normalize the brightness of the given Image img by:
1. computing the average brightness of the picture:
- this can be done by calculating the average brightness of each pixel
in img (the average brightness of each pixel is the sum of the values
of red, blue and green of the pixel, divided by 3 as a float division)
- the average brightness of the picture is then the sum of all the
pixel averages, divided by the product of the width and height of img
2. find the factor, let's call it x, which we can multiply the
average brightness by to get the value of 128
3. multiply the colors in each pixel by this factor x
"""
img_width, img_height = img.size
pixels = img.load() # create the pixel map
h = 0.0
for i in range(img_width):
for j in range(img_height):
r, g, b = pixels[i, j]
avg = sum(pixels[i, j]) / 3
h += avg
total_avg = h / (img_width * img_height)
x = int(128 // total_avg)
for i in range(img_width):
for j in range(img_height):
r, g, b = pixels[i, j]
pixels[i, j] = (min(255, r * x), min(255, g * x), min(255, b * x))
return img
So basically that is my take on the following function but for some reason it does not work. I believe my calculations and steps are what the docstring has told me to do but I am lost where to go from here.