在PIL中不使用内置函数调亮或调暗图像
我在做一个大学项目,使用的是PIL库。在这个项目中,有一个任务是要在不使用PIL的任何功能的情况下,让一张图片变暗或变亮。这个函数需要三个参数:原始文件名、动作('lighten'表示变亮,'darken'表示变暗)和程度(以百分比表示,是一个0到100之间的整数)。这是我目前写的代码:
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 个回答
2
这是一个关于整数除法的问题,出现在 (extent/100)
这个表达式里。要解决这个问题,你可以:
使用浮点数常量
extent/100.0
如果某个数是常量,这个方法很方便。
把分子或分母转换成浮点数
float(extent)/a_hundred
如果没有数是常量的话,可以用这个方法。
确保 /
是浮点数除法
from __future__ import division
你可以在源文件的开头插入这个,就像其他的 __future__
声明一样。
用 -Qnew 参数启动 python
python -Qnew
如果你在用 python2 的话,其他情况就不用了。
直接使用 python3 :)
在所有情况下, //
依然是整数除法。