开发者

Inverting image using the Python Image Library module

开发者 https://www.devze.com 2022-12-31 07:42 出处:网络
I\'m interested in learning how to invert (make a nega开发者_C百科tive of) an image using the python image libary module.

I'm interested in learning how to invert (make a nega开发者_C百科tive of) an image using the python image libary module.

I cannot however, use the ImageOps function 'invert.' I need another solution, using the RGB values. I've searched and tried to no avail.


Just subtract each RGB value from 255 (or the max) to obtain the new RGB values. this post tells you how to get the RBG values from a picture.


One obvious way is to use Image.getpixel and Image.putpixel, for RGB, each should be a tuple of three integers. You can get (255-r, 255-g, 255-b), then put it back.

Or use pix = Image.load(), which seems faster.

Or if you look into ImageOps.py, it's using a lookup table (lut list) to map an image to an inverted one.

Or if it's not against the rules of your assignment, you may use Numpy. Then you can use the faster matrix operation.


If you are working with the media module, then you could do this:

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:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消