使用Python图像库模块反转图像

1 投票
3 回答
4200 浏览
提问于 2025-04-15 22:52

我想学习如何使用Python的图像库来反转一张图片,也就是把它变成负片。

不过,我不能使用ImageOps里的'invert'这个功能。我需要另外一种方法,得用RGB值来实现。我搜索过很多次,但都没找到合适的办法。

3 个回答

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!'

希望这对你有帮助

0

只需要把每个RGB值从255(或者最大值)减去,就能得到新的RGB值。这篇文章教你怎么从图片中获取RGB值。

0

一种明显的方法是使用Image.getpixel和Image.putpixel。对于RGB颜色,每个颜色值应该是一个包含三个整数的元组。你可以通过计算(255-r, 255-g, 255-b)来得到反转的颜色,然后再把它放回去。

或者你可以使用pix = Image.load(),这似乎会更快一些。

再或者,如果你查看一下ImageOps.py,它使用了一个查找表(lut列表)来将图像映射到反转后的图像。

最后,如果你的作业规则允许的话,你可以使用Numpy。这样你就可以使用更快的矩阵运算。

撰写回答