函数使用python模块图像删除图像中的红色

函数使用python模块图像删除图像中的红色,python,image,colors,rgb,Python,Image,Colors,Rgb,我试图从网上自学python。以前没有prg经验。需要关于如何使用python中的“image”模块编写函数以从imgae中删除red的帮助。下面是我试图编写的代码…请提供帮助 import image img = image.Image("luther.jpg") newimg = image.EmptyImage(img.getWidth(),img.getHeight()) win = image.ImageWin() def no_red(): for col in ra

我试图从网上自学python。以前没有prg经验。需要关于如何使用python中的“image”模块编写函数以从imgae中删除red的帮助。下面是我试图编写的代码…请提供帮助

import image

img = image.Image("luther.jpg")

newimg = image.EmptyImage(img.getWidth(),img.getHeight())

win = image.ImageWin()

def no_red():
    for col in range(img.getWidth()):
        for row in range(img.getHeight()):
            p = img.getPixel(col,row)
            newred = 0
            newgreen = p.getGreen()
            newblue = p.getBlue()
            newpixel = image.Pixel(newred,newgreen,newblue)
    return newimg.setPixel(col,row,newpixel)



print (newimg.getPixel(45,52))
win.exitonclick()
我做错了什么?任何指导都会有帮助:)


关于>>

对于循环,您必须在
内调用
newimg.setPixel
,否则它将只替换图像末尾的一个像素:

def no_red():
    for col in range(img.getWidth()):
        for row in range(img.getHeight()):
            p = img.getPixel(col,row)
            newred = 0
            newgreen = p.getGreen()
            newblue = p.getBlue()
            newpixel = image.Pixel(newred,newgreen,newblue)
            newimg.setPixel(col,row,newpixel)
您也没有在任何地方呼叫
no\u red
。我建议改为这样写:

def no_red(image):
    new_image = ... # make a copy of image
    # original code that removes red subpixels
    return new_image
然后打电话:

new_image = no_red(original_image)

在我看来,这是最简单的方法

如果您不想陷入循环,您可能会发现以下几行更有用。以下几行从图像测试中删除红色

def removeColour():
        img =  Image.open('test.png').convert('RGB')
        source = img.split()
        R, G, B = 0, 1, 2
        out = source[R].point(lambda i: i * 0)
        source[R].paste(out, None, None)
        img = Image.merge(img.mode, source)
        img.save('testNoRed.png')
        img.show()
def removeColour():
        img =  Image.open('test.png').convert('RGB')
        source = img.split()
        R, G, B = 0, 1, 2
        out = source[R].point(lambda i: i * 0)
        source[R].paste(out, None, None)
        img = Image.merge(img.mode, source)
        img.save('testNoRed.png')
        img.show()