首页 > 解决方案 > 标准化图像的亮度

问题描述

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

所以基本上这就是我对以下功能的看法,但由于某种原因它不起作用。我相信我的计算和步骤是文档字符串告诉我要做的,但我迷失了从这里去哪里。

标签: pythonpython-3.xpython-imaging-library

解决方案


推荐阅读