为图像中的每个像素添加值以调整颜色。Python3

2024-05-13 08:15:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要写一个程序,读取红色,绿色和蓝色的值,并将该值添加到图像中的每个像素以调整颜色。在

下面是一个例子,我在每个像素的绿色值上增加了40,但没有给红色和蓝色通道添加任何内容:

File name: dragonfly.png
Red tint: 0
Green tint: 40
Blue tint: 0

我的代码在下面,它运行。但当我提交时,它说“提交创建了输出图像png输出,但与预期的输出图像不匹配。“我附上了两张图片-实际的和预期的。在

请参阅我的代码:

^{pr2}$

我的代码哪里做错了?谢谢你

实际图片actual picture

预期结果expected outcome


Tags: 代码name图像程序内容png颜色图片
3条回答

我不知道这段代码实际产生了什么,但不是img.putpixel()创建一个类似px = img.load()的像素映射,然后使用px[x,y] = new_color

编辑:

我的理解是你只需要根据用户的输入编辑图像。那么为什么不把RGB值加到每个值上呢?我还没有测试这个代码。在

for y in range(img.height):
    for x in range(img.width):
        current_color = px[x,y]
        new_color = (current_color[0] + int(red_tint), current_color[1] + int(green_tint), current_color[2] + int(blue_tint))
        px[x,y] = new_color

我也遇到了同样的问题,在分析了每个人的答案后,我找到了解决办法

    from PIL import Image
    file = input("File name: ")
    red_tint = int(input("Red tint: "))
    green_tint = int(input("Green tint: "))
    blue_tint = int(input("Blue tint: "))
    img = Image.open(file)
    red, green, blue = img.split()
    for y in range(img.height):
       for x in range(img.width):
       value = img.getpixel((x, y))
       new_color = (value[0] + int(red_tint), value[1] + int(green_tint), value[2] + int(blue_tint))
       img.putpixel((x, y), new_color)
    img.save('output.png')

希望这有帮助

编辑: 这里是最矢量化的方法,它可以正确处理255以上的整数

import Image
import numpy as np

r = int(input('Red: '))
g = int(input('Green: '))
b = int(input('Blue: '))

np_img = np.array(img, dtype = np.float32)

np_img[:,:,0] += r
np_img[:,:,1] += g
np_img[:,:,2] += b

np_img[np_img > 255] = 255
np_img = np_img.astype(np.uint8)

img = Image.fromarray(np_img, 'RGB')
img.save('output.png')

相关问题 更多 >