Working with images in Python

Installation :

  • Linux: In the Linux terminal, enter the following:
     pip install Pillow 

    Install pip via terminal:

     sudo apt-get update sudo apt-get install python-pip 
  • Windows: Download the appropriate Pillow package according to your Python version. Be sure to download according to the version of Python you have.

Here we will be working with the Image module, which provides a class of the same name and provides many functions for working with our images. To import the Image module, our code must start with the following line:

 from PIL import Image 

Image manipulation:

  • Open a specific image from path:

    # img = Image.open (path)
    # On successful execution of this statement,
    # an Image object is returned and stored in the img variable)

     

    try

    img  = Image . open (path) 

    except IOError:

      pass

    # Use the above statement in the try block as it may
    # raise an IOError if the file cannot be found
    # or the image cannot be opened.

  • Get image size . Instances of the Image class have many attributes, one of its useful attributes is size.

    from PIL import Image

     

    filename = "image.png"

    with Image. open (filename) as image:

    width, height = image.size

    # Image.size gives 2 tuples and a width, the height can be obtained

    Some other attributes: Image.width, Image.height, Image.format, Image.info etc.

  • Save changes to the image: to save any changes you made to the image file we need to provide a path as well image format.

    img.save (path, format

    # format is optional if no format is specified
    # determined from filename extension

  • Image rotation. Image rotation angle is required as a parameter to rotate the image.

    from PIL import Image

      

    def main ():

    try :

    # Relative path

    img = Image. open ( "picture.jpg"

     

    # Angle given

    img = img.rotate ( 180

      

      # Saved in the same location

      img.save ( "rotated_picture.jpg" )

    except IOError:

    pass

     

    if __ name__ = = "__ main__" :

    main ()

    Note. An optional extension flag is available as one of the arguments to the rotate method, which, if set to true, expands the output image to make it large enough to accommodate the fully rotated image.
    As you can see from the above code snippet, I used a relative path where my image is in the same directory as my Python code file, an absolute path can also be used.

  • Cropping an image: Image.crop (rectangle) takes a four-pixel (left, top, right, bottom) pixel coordinate and returns a rectangular area from the used image.

    from PIL import Image

     

    def main ():

    try :

    # Relative path

    img = Image . open ( "picture.jpg" )

    width, height = img.size

     

    area = ( 0 , 0 , width / 2 , height / 2 )

      img = img.crop (area)

      

    # Saved in the same location

    img.save ( "cropped_picture.jpg"

     

    except IOError:

    pass

     

    if __ name__ = = "__ main__" :

      main ()

  • Image resizing: Image.resize (size) — here size is specified as width and height in 2 tuples.

    from PIL import Image

      

    def main ():

    try :

    # Relative path

    img = Image. open ( "picture.jpg" )

    width, height = img.size

      

    img = img.resize ((width / 2 , height / 2 ))

     

      # Saved in the same location

    img.save ( "resized_picture.jpg"

    except IOError:

      pass

     

    if __ name__ = = "__ main__" :

    main ()

  • Inserting an image into another image: the second argument can be a 2-tuple (with the top left corner) or a 4-tuple (left, top, right, bottom) — in this case, the size of the inserted image must match the size of this block area, or None, which is equivalent to (0, 0).

    from PIL import Image

     

    def main ():

      try :

      # Relative path

    # Image, into which we want to insert

    img = Image. open ( "picture.jpg"

     

    # Relative path

    # The image we want to insert

    img2 = Image. open ( "picture2.jpg"

    img.paste (img2, ( 50 , 50 ))

     

    # Saved in the same location

      img.save ( " pasted_picture.jpg " )

     

    except IOError:

      pass

     

    if __ name__ = = " __ main__ " :

    main ()

     
    ## An optional argument is also available for an optional image mask image.

  • Getting image histogram. Returns the image histogram as a list of the number of pixels, one for each pixel in the image. (An image histogram is a graphical representation of the tonal distribution in a digital image. It contains all the brightness values ​​contained in the image. It displays the number of pixels for each brightness value. It helps with exposure adjustments.)
    from PIL import Image

    def main ():

    try :

      # Relative path

    img = Image. open ( "picture.jpg"

     

      # Get image histogram

    print img.histogram ()

     

    except IOError:

      pass

     

    if __ name__ = = " __ main__ " :

    main ()

  • Image Transpose: this function gives us a mirror image of the image

    from PIL import Image

     

    def main ():

    try :

    # Relative path

      img = Image. open ( "picture.jpg"

     

    # image transpose

    transposed_img = img. transpose (Image.FLIP_LEFT_RIGHT)

     

    # Save transposed image

    transposed_img.save ( "transposed.jpg" )

      except IOError :

    pass

      

    if __ name__ = = "__ main__" :

    main ()

  • Split the image into separate stripes. splitting an RGB image creates three new images, each containing a copy of the original individual stripes.

    from PIL import Image

     

    def main ():

      try :

      # Relative path

    img = Image. open ( "picture.jpg"

      

      # splitting the image

    print img.split ()

    except IOError:

    pass

     

    if __ name__ = = "__ main__" :

    main ()

  • tobitmap: convert the image to an X11 bitmap (plain text binary image format). Returns a string containing an X11 bitmap, it can only be used for images in “1” mode, that is, for black and white images with 1-bit pixels.
    from PIL import Image

    def main ():

    try :

    # Relative path

    img = Image. open ( "picture.jpg"

    print img.mode

      

      # convert image to bitmap

      print img.tobitmap ()

      

      print type (img.tobitmap ())

    except IOError:

    pass

     

    if __name__ = = "__ main__" :

    main ()

  • Create a thumbnail. This method creates a thumbnail of an open image. It does not return a new image object, it makes changes in place of the currently open image object. If you don`t want to modify the original image object, create a copy and then apply this method. This method also evaluates the appropriateness of maintaining the aspect ratio of the image in accordance with the transmitted size.
    from PIL import Image

    def main ():

    try :

    # Relative path

    img = Image. open ( "picture.jpg"

     

    # In-place modification

    img.thumbnail (( 200 , 200 )) 

     

    img.save ( "thumb.jpg" )

    except IOError:

    pass

     

    if __ name__ = = " __ main__ " :

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  main ()

This article is provided by Mohit Agarwal . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.