Python: Image Manipulation
This page is a shorter documentation of the Python Imaging Library’s Image capabilities. The full documentation for the entire library is at https://pillow.readthedocs.io/en/stable/ and the documentation for the Image module (class) is at https://pillow.readthedocs.io/en/stable/reference/Image.html.
First, you need to have the PIL module installed in your Python installation. On Ubuntu and probably other Linux distros, this is the package “python-imaging”, and you can do “sudo apt-get install python-imaging”. Other platforms you will have to figure out.
At the top your Python program you must add the line “from PIL import Image” if you want to use “Image” directly (as the examples below do), but you can also do “import PIL” and then use “PIL.Image” everywhere.
In the examples below I use some variables, but just remember that you can use any variable names you want. The “open” and “new” commands are invoked from the Image module directly, and so need prefixed with the capital-I Image name; you cannot change this.
image = Image.open(filename)
This sets the variable “image” to hold a new image object that is contains the image from the given file. This works for most image file types – the file type is inferred from the filename (e.g., “mypic.jpg” is a JPEG image).
image = Image.new(mode, size, [color])
This sets the variable “image” to hold a new image object created as a “blank” image of the given size. You should always use a mode of “RGB”, and size is a tuple of the width and height in pixels of the image. Color is optional (that is what the square brackets mean). For example, Image.new(“RGB”,(300,200),(0,255,0)) creates a new RGB image that is 300 pixels wide by 200 pixels high, and each pixel is initialized to pure green. The commands below are not with the capital-I Image, but lowercase, meaning it is just a variable name that contains an image object. Your variable can be any name you want.
pixel = image.getpixel(xyTuple)
This function returns the pixel value that is at the given x,y coordinates. Also note that the x,y coordinates are a tuple, so you probably need to use double-parentheses when you call this. For example image.getpixel((30,40)) returns the pixel value at 30,40. The return value is a 3-tuple of each of the RGB color components.
image.putpixel(xyTuple,colorTuple)
This sets a pixel in the image to a new value; the location is the first parameter, the color the second. For example, image.putpixel((30,40),(100,200,100)) would set the pixel at 30,40 to be some sort of green (red and blue are equal and so just brighten the green somewhat).
image.size
This is the size of the image, given as an XY tuple.
image.save(filename , [...])
This will save the current image to the named file. There are further options if you want them. See the official documentation.
image.show()
This will open a viewer window (separate program) that displays the current image.