PIL中的图像变亮或变暗,没有内置功能

时间:2011-05-28 11:00:55

标签: python python-imaging-library

我正在将PIL用于uni项目,我们有一项任务,我们必须使图像变暗或变亮,而不使用PIL的任何功能。该函数采用原始文件名,操作('变亮'或'变暗')和范围(以百分比表示 - 介于0和100之间的int)。这是我到目前为止所提出的:

from PIL import Image

def change_brightness(filename, action, extent):
    """
    This function either increases or decreases the brightness of an image
    by altering each pixel in each band

    """
    #load the original image into a list
    original_image = Image.open(filename, 'r')
    pixels = original_image.getdata()

    #initialise the new image
    new_image = Image.new('RGB', original_image.size)
    new_image_list = []

    brightness_multiplier = 1.0

    if action == 'lighten':
        brightness_multiplier += (extent/100)
    else:
        brightness_multiplier -= (extent/100)

    #for each pixel, append the brightened or darkened version to the new image list
    for pixel in pixels:
        new_pixel = (int(pixel[0] * brightness_multiplier),
                     int(pixel[1] * brightness_multiplier),
                     int(pixel[2] * brightness_multiplier))

        #check the new pixel values are within rgb range
        for pixel in new_pixel:
            if pixel > 255:
                pixel = 255
            elif pixel < 0:
                pixel = 0

        new_image_list.append(new_pixel)

    #save the new image
    new_image.putdata(new_image_list)
    new_image.save('colour_brightness.jpg')

当我运行它时,新图像不会从原始图像修改(除了一些新的jpg文物)。我尝试brightness_multiplier有一个显式值(1.1为亮,0.9为暗)并且它有效,所以当我从extent获取值时,我不知道为什么它不起作用参数。

如果有人能说出一些亮点,我们将不胜感激!

1 个答案:

答案 0 :(得分:1)

这是(extent/100)表达式中的整数除法问题。为了纠正这个问题,你可以:

使用浮点文字

extent/100.0

如果术语是文字,则很方便。

将分子或分母转换为float

float(extent)/a_hundred

如果没有术语是文字。

确保/是浮点除法

from __future__ import division

将其插入源文件的开头,与所有__future__语句一样。

使用-Qnew

调用python
python -Qnew

如果使用python2,否则

使用python3:)

在所有情况下,//仍为整数除法。