简体   繁体   English

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

[英]Inverting image using the Python Image Library module

I'm interested in learning how to invert (make a negative of) an image using the python image libary module. 我对学习如何使用python image libary模块反转图像(使图像为负)感兴趣。

I cannot however, use the ImageOps function 'invert.' 但是,我不能使用ImageOps函数“反转”。 I need another solution, using the RGB values. 我需要使用RGB值的另一种解决方案。 I've searched and tried to no avail. 我已搜索并尝试无济于事。

Just subtract each RGB value from 255 (or the max) to obtain the new RGB values. 只需从255(或最大值)中减去每个RGB值即可获得新的RGB值。 this post tells you how to get the RBG values from a picture. 这篇文章告诉您如何从图片中获取RBG值。

One obvious way is to use Image.getpixel and Image.putpixel, for RGB, each should be a tuple of three integers. 一种明显的方法是使用Image.getpixel和Image.putpixel,对于RGB,每个都应该是三个整数的元组。 You can get (255-r, 255-g, 255-b), then put it back. 您可以得到(255-r,255-g,255-b),然后放回去。

Or use pix = Image.load(), which seems faster. 或者使用pix = Image.load(),它看起来更快。

Or if you look into ImageOps.py, it's using a lookup table (lut list) to map an image to an inverted one. 或者,如果您查看ImageOps.py,则它使用查找表(lut列表)将图像映射到反向图像。

Or if it's not against the rules of your assignment, you may use Numpy. 或者,如果这不违反您的分配规则,则可以使用Numpy。 Then you can use the faster matrix operation. 然后,您可以使用更快的矩阵运算。

If you are working with the media module, then you could do this: 如果您正在使用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!'

The process is similar if you are using the picture module, and looks like this: 如果您使用的是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!'

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM