簡體   English   中英

為圖像中的每個像素增加值以調整顏色。 Python 3

[英]Add value to every pixel in the image to adjust the colours. Python 3

我需要編寫一個程序來讀取紅色,綠色和藍色的值,並將該值添加到圖像中的每個像素以調整顏色。

這是一個示例,其中我向每個像素的綠色值添加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')

我的代碼在做什么錯? 謝謝

實際圖片 實際圖片

預期結果 預期結果

這里有點拉伸,因為我不知道代碼實際生成的是什么,但是代替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

編輯:這是最正確處理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')

我遇到的問題與做同樣的問題相同,在分析了每個人的答案后,我找到了解決方案

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

希望這有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM