我正试图从网上自学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()
我在做错了什么?任何指导都会有所帮助:)
问候>>
答案 0 :(得分:1)
您必须在newimg.setPixel
循环内调用for
,否则它只会在图像末尾一直替换一个像素:
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_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)
答案 1 :(得分:1)
for i in range(img.getWidth()):
for j in range(img.getHeight()):
old_pixel = img.getPixel(i, j)
new_pixel = image.Pixel(0, old_pixel.getGreen(), old_pixel.getBlue())
new_image.setPixel(i, j, new_pixel)
这是我认为最简单的方法
答案 2 :(得分:1)
如果您不想陷入循环,您可能会发现以下几行更有用。以下行从图像测试中删除RED。
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()