首页 > 解决方案 > 枕头改变图片的RGB值不起作用

问题描述

我正在尝试缩放图像的 rgb 值。

我学到的方法是通过做getpixel每个putpixel像素。

import PIL
from PIL import Image
from PIL import ImageEnhance
from PIL import ImageFont,ImageDraw

# read image and convert to RGB
image=Image.open("readonly/msi_recruitment.gif")
image=image.convert('RGB')

# build a list of 9 images which have different brightnesses
images=[]
intensity = [0.1, 0.5, 0.9]
channel=[0,1,2] 

for c in channel:
    for i in intensity:
        newImage = PIL.Image.new(image.mode, (image.width, image.height+100))
        newImage.paste(image,(0,0))
        
        text="channel {} intensity {}".format(c, i)
        font = ImageFont.truetype(r'readonly/fanwood-webfont.ttf', 75)  
        Draw=ImageDraw.Draw(newImage)
        Draw.text((10,470), text, fill="white", font=font, align="left")
        
        
        for row in range(image.height):
            for col in range(image.width):
                p = image.getpixel((col, row)) # p as RGB pixel values
                
                if channel == 0:
                    newImage.putpixel((col, row), (int(p[0]*i),p[1],p[2]))
                elif channel == 1:
                    newImage.putpixel((col, row), (p[0],int(p[1]*i),p[2]))    
                elif channel == 2:
                    newImage.putpixel((col, row), (p[0],p[1],int(p[2]*i)))    
        
        images.append(newImage)

但是,它不起作用,像素的 RGB 没有改变。

  1. 我的代码有什么问题?

  2. 有没有办法将图片的 RGB 值作为一个整体进行缩放,而不是逐个像素地循环?

标签: pythonimagepython-imaging-libraryrgb

解决方案


要修复您的代码,请更改channelc

if c == 0:
    newImage.putpixel((col, row), (int(p[0]*i),p[1],p[2]))
elif c == 1:
    newImage.putpixel((col, row), (p[0],int(p[1]*i),p[2]))    
elif c == 2:
    newImage.putpixel((col, row), (p[0],p[1],int(p[2]*i))) 

要查看其他方法,请参阅Mark Setchell 的这个答案


推荐阅读