使用Python Image Library模块反转图像

时间:2010-05-19 03:30:21

标签: python image-manipulation python-imaging-library

我有兴趣学习如何使用python图像库模块反转(减去)图像。

但是我不能使用ImageOps功能'反转'。我需要另一种解决方案,使用RGB值。我搜索过并试图无济于事。

3 个答案:

答案 0 :(得分:0)

只需从255(或最大值)中减去每个RGB值,即可获得新的RGB值。 this post告诉您如何从图片中获取RBG值。

答案 1 :(得分:0)

一种显而易见的方法是使用Image.getpixel和Image.putpixel,对于RGB,每个应该是三个整数的元组。你可以得到(255-r,255-g,255-b),然后把它放回去。

或者使用pix = Image.load(),这似乎更快。

或者如果您查看ImageOps.py,它会使用查找表(lut list)将图像映射到倒置图像。

或者,如果不违反作业规则,您可以使用Numpy。然后你可以使用更快的矩阵运算。

答案 2 :(得分:0)

如果您正在使用media模块,那么您可以这样做:

import media
def invert():
    filename = media.choose_file()    # opens a select file dialog
    pic = media.load_picture(filename)    # converts the picture file into a "picture" as recognized by the module.
    for pixel in pic:
        media.set_red(pixel, 255-media.get_red(pixel))    # the inverting algorithm as suggested by @Dingle
        media.set_green(pixel, 255-media.get_green(pixel))
        media.set_blue(pixel, 255-media.get_blue(pixel))
print 'Done!'

如果您使用picture模块,过程类似,如下所示:

import picture
def invert():
    filename = picture.pick_a_file()    # opens a select file dialog
    pic = picture.make_picture(filename)    # converts the picture file into a "picture" as recognized by the module.
    for pixel in picture.get_pixels(pic):
        picture.set_red(pixel, 255-picture.get_red(pixel))    # the inverting algorithm as suggested by @Dingle
        picture.set_green(pixel, 255-picture.get_green(pixel))
        picture.set_blue(pixel, 255-picture.get_blue(pixel))
print 'Done!'

希望这有帮助