views:

125

answers:

3

Good day chaps.

I'm interested in learning how to invert (make a negative 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. Thanks for any help :)

A: 

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.

YGL
A: 

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.

Dingle
A: 

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

inspectorG4dget