Skip to main content
 首页 » 编程设计

python之在 Python 中将图像处理为棕褐色调

2025年04月02日15zhengyun_ustc

我需要帮助弄清楚如何将图像转换为棕褐色。这是我到目前为止所拥有的……但它只会将所有内容更改为黑色和白色,并带有很小的棕色。我不确定我做错了什么:(

import image 
 
def convertSepia(input_image): 
    grayscale_image = image.EmptyImage(input_image.getWidth(), input_image.getHeight()) 
 
    for col in range(input_image.getWidth()): 
        for row in range(input_image.getHeight()): 
            p = input_image.getPixel(col, row) 
 
            R = p.getRed() 
            G = p.getGreen() 
            B = p.getBlue() 
 
            newR = (R * 0.393 + G * 0.769 + B * 0.189) 
            newG = (R * 0.349 + G * 0.686 + B * 0.168) 
            newB = (R * 0.272 + G * 0.534 + B * 0.131) 
 
            newpixel = image.Pixel(newR, newG, newB) 
            grayscale_image.setPixel(col, row, newpixel) 
 
    sepia_image = image.EmptyImage(input_image.getWidth(), input_image.getHeight()) 
    for col in range(input_image.getWidth()): 
        for row in range(input_image.getHeight()): 
            p = grayscale_image.getPixel(col, row) 
            red = p.getRed() 
            if red > 140: 
                val = (R * 0.393 + G * 0.769 + B * 0.189) 
            else: 
                val = 0 
            green = p.getGreen() 
            if green > 140: 
                val = (R * 0.349 + G * 0.686 + B * 0.168) 
            else: 
                val = 0 
            blue = p.getBlue() 
            if blue > 140: 
                val = (R * 0.272 + G * 0.534 + B * 0.131) 
            else: 
                val = 0 
 
            newpixel = image.Pixel(val, val, val) 
            sepia_image.setPixel(col, row, newpixel) 
    return sepia_image 
 
 
win = image.ImageWin() img = image.Image("luther.jpg") 
 
sepia_img = convertSepia(img) sepia_img.draw(win) 
 
win.exitonclick() 

还有关于从这里去哪里的更多提示吗?谢谢:)

请您参考如下方法:

您的灰度图像不是灰度图像。在灰度图像中,所有三个 channel r、g、b 都具有相同的值。

打开画图并尝试验证您的代码是否有意义。

修复这些行:

newR = (R * 0.393 + G * 0.769 + B * 0.189) 
newG = (R * 0.349 + G * 0.686 + B * 0.168) 
newB = (R * 0.272 + G * 0.534 + B * 0.131) 

简单的用r,g,b的均值放入newR, newG 和 newG。

还有一些加权方法。只需谷歌搜索 RGB 到强度的公式。