【问题标题】:Add value to every pixel in the image to adjust the colours. Python 3为图像中的每个像素添加值以调整颜色。蟒蛇 3
【发布时间】:2018-10-05 03:46:56
【问题描述】:

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

这是一个示例,我将 40 添加到每个像素的绿色值,但不向红色和蓝色通道添加任何内容:

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

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

请看我的代码:

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)
r,g,b = img.getpixel( (0,0) )
for y in range(img.height):
    for x in range(img.width):
        current_color = (r,g,b)
        if current_color == r:
            R = r + red_tint
        if current_color == g:
            G = g + green_tint
        if current_color == b:
            B = b + blue_tint
        R, G, B = current_color
        new_color = (R, G, B)
        img.putpixel((x, y), new_color)
img.save('output.png')

我在代码中做错了什么?谢谢

实物图

预期结果

【问题讨论】:

  • 您的程序输出的文件看起来像预期的结果吗?另外:R、G 和 B 应该在你的循环中是什么?您实际上从未在代码中获得像素 (x, y)。看起来您只是将它们都设置为相同的值。
  • R,G,B 应该是 red,green,blue 的新值
  • 那么它们应该从旧值派生而来。您应该在循环中从像素 (x,y) 获取 rgb 值。
  • @GarrettGutierrez 你能解释一下如何做吗?无论我一直试图做什么 - 都行不通。谢谢

标签: python image pixel


【解决方案1】:

这里有点牵强,因为我不知道代码实际产生了什么,但不是 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

【讨论】:

  • 看起来我得到的是纯色图片
【解决方案2】:

编辑: 这是正确处理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')

【讨论】:

    【解决方案3】:

    我在做同样的问题时遇到了同样的问题,在分析了每个人的答案后,我找到了解决方案

        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')
    

    希望对您有所帮助

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2012-05-07
    相关资源
    最近更新 更多