Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pillow Basic Image Operations

Pillow Basic Image Operations

After installing the Pillow library, we need to import the necessary modules:

# 导入模块

from PIL import Image, ImageFilter, ImageEnhance, ImageDraw, ImageFont

import os

Test image (download to local for testing):

Example

The following complete example demonstrates the following operations:

  1. Open and display basic image information
  2. Format, size, mode, etc.
  3. - Format, size, mode, etc.
    1. Resize the image
    2. Resize the image to a specified size
    3. - Resize the image to a specified size
      1. Crop the image
      2. Extract a specific region from the original image
      3. - Extract a specific region from the original image
        1. Rotate an image
        2. Rotate 45 degrees and keep the complete image
        3. - Rotate 45 degrees and keep the complete image
          1. Flip the image
          2. Horizontal and vertical flip
          3. - Horizontal and vertical flip
            1. Convert color mode
            2. Convert a color image to grayscale
            3. - Convert a color image to grayscale
              1. Apply filters
              2. Effects such as blur, edge enhancement, contour, etc.
              3. - Effects such as blur, edge enhancement, contour, etc.
                1. Adjust image properties
                2. Brightness, contrast, and sharpness adjustment
                3. - Brightness, contrast, and sharpness adjustment
                  1. Add text
                  2. Draw text on the image
                  3. - Draw text on the image
                    1. Merge images
                    2. Simple image stitching
                    3. - Simple image stitching
                      1. Save in different formats and qualities
                      2. PNG, BMP, and JPEG with different qualities
                      3. - PNG, BMP, and JPEG with different qualities

                        Example

                        """
                        Python Pillow Basic Image Operations Tutorial
                        Test image used: tiger.jpeg
                        """

                        from

                        PIL

                        import

                        Image

                        ,

                        ImageFilter

                        ,

                        ImageEnhance

                        ,

                        ImageDraw

                        ,

                        ImageFont

                        import

                        os

                        def

                        main

                        (

                        )

                        :

                           

                        Ensure there is an output folder in our working directory

                            output_dir

                        =

                        "output"

                           

                        if

                        not

                        os

                        .

                        path

                        .

                        exists

                        (

                        output_dir

                        )

                        :

                               

                        os

                        .

                        makedirs

                        (

                        output_dir

                        )

                           

                           

                        1. Open the image

                           

                        print

                        (

                        "1. Open the image"

                        )

                           

                        try

                        :

                                img

                        =

                        Image.

                        open

                        (

                        "tiger.jpeg"

                        )

                               

                        print

                        (

                        f

                        "Successfully opened image - format: {img.format}, size: {img.size}, mode: {img.mode}"

                        )

                           

                        except

                        Exception

                        as

                        e:

                               

                        print

                        (

                        f

                        "Unable to open image: {e}"

                        )

                               

                        return

                           

                           

                        2. Display basic image information

                           

                        print

                        (

                        "\n2. Basic image information"

                        )

                           

                        print

                        (

                        f

                        "Image format: {img.format}"

                        )

                           

                        print

                        (

                        f

                        "Image size (width x height): {img.size}"

                        )

                           

                        print

                        (

                        f

                        "Image mode: {img.mode}"

                        )

                           

                           

                        3. Resize the image

                           

                        print

                        (

                        "\n3. Resize the image"

                        )

                            resized_img

                        =

                        img.

                        resize

                        (

                        (

                        400

                        ,

                        300

                        )

                        )

                            resized_img.

                        save

                        (

                        f

                        "{output_dir}/resized_tiger.jpg"

                        )

                           

                        print

                        (

                        "Saved the resized image"

                        )

                           

                           

                        4. Crop the image

                           

                        print

                        (

                        "\n4. Crop the image"

                        )

                           

                        Crop area (left, top, right, bottom)

                            width

                        ,

                        height

                        =

                        img.

                        size

                            crop_area

                        =

                        (

                        width//

                        4

                        ,

                        height//

                        4

                        ,

                        3

                        *width//

                        4

                        ,

                        3

                        *height//

                        4

                        )

                         

                        Crop the middle area

                            cropped_img

                        =

                        img.

                        crop

                        (

                        crop_area

                        )

                            cropped_img.

                        save

                        (

                        f

                        "{output_dir}/cropped_tiger.jpg"

                        )

                           

                        print

                        (

                        f

                        "Cropped image area {crop_area} and saved"

                        )

                           

                           

                        5. Rotate the image

                           

                        print

                        (

                        "\n5. Rotate the image"

                        )

                            rotated_img

                        =

                        img.

                        rotate

                        (

                        45

                        ,

                        expand

                        =

                        True

                        )

                         

                        Rotate 45 degrees, expand=True keeps the entire image

                            rotated_img.

                        save

                        (

                        f

                        "{output_dir}/rotated_tiger.jpg"

                        )

                           

                        print

                        (

                        "Saved the rotated image"

                        )

                           

                           

                        6. Flip the image

                           

                        print

                        (

                        "\n6. Flip the image"

                        )

                           

                        Horizontal flip

                            h_flipped

                        =

                        img.

                        transpose

                        (

                        Image.

                        FLIP_LEFT_RIGHT

                        )

                            h_flipped.

                        save

                        (

                        f

                        "{output_dir}/horizontal_flip_tiger.jpg"

                        )

                           

                        Vertical flip

                            v_flipped

                        =

                        img.

                        transpose

                        (

                        Image.

                        FLIP_TOP_BOTTOM

                        )

                            v_flipped.

                        save

                        (

                        f

                        "{output_dir}/vertical_flip_tiger.jpg"

                        )

                           

                        print

                        (

                        "Saved the horizontally and vertically flipped images"

                        )

                           

                           

                        7. Convert color mode

                           

                        print

                        (

                        "\n7. Convert color mode"

                        )

                            grayscale_img

                        =

                        img.

                        convert

                        (

                        'L'

                        )

                         

                        Convert to grayscale

                            grayscale_img.

                        save

                        (

                        f

                        "{output_dir}/grayscale_tiger.jpg"

                        )

                           

                        print

                        (

                        "Saved the grayscale image"

                        )

                           

                           

                        8. Apply filters

                           

                        print

                        (

                        "\n8. Apply filters"

                        )

                           

                        Blur filter

                            blurred_img

                        =

                        img.

                        filter

                        (

                        ImageFilter.

                        BLUR

                        )

                            blurred_img.

                        save

                        (

                        f

                        "{output_dir}/blurred_tiger.jpg"

                        )

                           

                        Edge enhancement

                            edge_img

                        =

                        img.

                        filter

                        (

                        ImageFilter.

                        EDGE_ENHANCE

                        )

                            edge_img.

                        save

                        (

                        f

                        "{output_dir}/edge_enhanced_tiger.jpg"

                        )

                           

                        Contour filter

                            contour_img

                        =

                        img.

                        filter

                        (

                        ImageFilter.

                        CONTOUR

                        )

                            contour_img.

                        save

                        (

                        f

                        "{output_dir}/contour_tiger.jpg"

                        )

                           

                        print

                        (

                        "Saved images with different filters applied"

                        )

                           

                           

                        9. Adjust brightness, contrast, and sharpness

                           

                        print

                        (

                        "\n9. Adjust image properties"

                        )

                           

                        Increase brightness

                            brightness

                        =

                        ImageEnhance.

                        Brightness

                        (

                        img

                        )

                            bright_img

                        =

                        brightness.

                        enhance

                        (

                        1.5

                        )

                         

                        Brightness increased by 50%

                            bright_img.

                        save

                        (

                        f

                        "{output_dir}/brighter_tiger.jpg"

                        )

                           

                           

                        Increase contrast

                            contrast

                        =

                        ImageEnhance.

                        Contrast

                        (

                        img

                        )

                            contrast_img

                        =

                        contrast.

                        enhance

                        (

                        1.5

                        )

                         

                        Contrast increased by 50%

                            contrast_img.

                        save

                        (

                        f

                        "{output_dir}/contrast_tiger.jpg"

                        )

                           

                           

                        Increase sharpness

                            sharpness

                        =

                        ImageEnhance.

                        Sharpness

                        (

                        img

                        )

                            sharp_img

                        =

                        sharpness.

                        enhance

                        (

                        2.0

                        )

                         

                        Sharpness increased by 100%

                            sharp_img.

                        save

                        (

                        f

                        "{output_dir}/sharper_tiger.jpg"

                        )

                           

                        print

                        (

                        "Saved the image with adjusted brightness, contrast, and sharpness"

                        )

                           

                           

                        10. Add text

                           

                        print

                        (

                        "\n10. Add text"

                        )

                           

                        Create a copy for drawing

                            text_img

                        =

                        img.

                        copy

                        (

                        )

                            draw

                        =

                        ImageDraw.

                        Draw

                        (

                        text_img

                        )

                           

                        Try using a system font, fall back to default if it fails

                           

                        try

                        :

                               

                        Different operating systems may require different font paths

                               

                        Windows font path example

                                font

                        =

                        ImageFont.

                        truetype

                        (

                        "arial.ttf"

                        ,

                        36

                        )

                           

                        except

                        IOError

                        :

                                font

                        =

                        ImageFont.

                        load_default

                        (

                        )

                           

                           

                        Add text on the image

                            draw.

                        text

                        (

                        (

                        10

                        ,

                        10

                        )

                        ,

                        "Tiger"

                        ,

                        fill

                        =

                        (

                        255

                        ,

                        255

                        ,

                        255

                        )

                        ,

                        font

                        =

                        font

                        )

                            text_img.

                        save

                        (

                        f

                        "{output_dir}/text_tiger.jpg"

                        )

                           

                        print

                        (

                        "Saved the image with text added"

                        )

                           

                           

                        11. Merge images (simple stitching)

                           

                        print

                        (

                        "\n11. Merge images"

                        )

                           

                        Create a new image with twice the width of the original and the same height

                            merged_img

                        =

                        Image.

                        new

                        (

                        'RGB'

                        ,

                        (

                        width*

                        2

                        ,

                        height

                        )

                        )

                           

                        Place the original image on the left

                            merged_img.

                        paste

                        (

                        img

                        ,

                        (

                        0

                        ,

                        0

                        )

                        )

                           

                        Place the grayscale image on the right

                            merged_img.

                        paste

                        (

                        grayscale_img.

                        convert

                        (

                        'RGB'

                        )

                        ,

                        (

                        width

                        ,

                        0

                        )

                        )

                            merged_img.

                        save

                        (

                        f

                        "{output_dir}/merged_tiger.jpg"

                        )

                           

                        print

                        (

                        "Saved the merged image"

                        )

                           

                           

                        12. Save in different formats

                           

                        print

                        (

                        "\n12. Save in different formats"

                        )

                            img.

                        save

                        (

                        f

                        "{output_dir}/tiger.png"

                        )

                         

                        PNG format

                            img.

                        save

                        (

                        f

                        "{output_dir}/tiger.bmp"

                        )

                         

                        BMP format

                           

                           

                        Save as JPEG, set quality

                            img.

                        save

                        (

                        f

                        "{output_dir}/tiger_high_quality.jpg"

                        ,

                        quality

                        =

                        95

                        )

                         

                        High quality

                            img.

                        save

                        (

                        f

                        "{output_dir}/tiger_low_quality.jpg"

                        ,

                        quality

                        =

                        10

                        )

                         

                        Low quality

                           

                        print

                        (

                        "Saved images in different formats and qualities"

                        )

                           

                           

                        print

                        (

                        "\nAll operations complete! Processed images are saved in the 'output' folder."

                        )

                        if

                        name

                        ==

                        "main"

                        :

                            main

                        (

                        )

                        The code is structured, with clear comments for each operation. All processed images are saved in the output directory for easy viewing and comparison.

                        How to use it:

                        If the above code executes successfully, the terminal output is:


                        Operation Description

                        1. Open the image and get basic information

                        Example

                        Open the image file

                        img

                        =

                        Image.

                        open

                        (

                        "tiger.jpeg"

                        )

                        Get and display image information

                        print

                        (

                        f

                        "Image format: {img.format}"

                        )

                         

                        e.g., JPEG, PNG, etc.

                        print

                        (

                        f

                        "Image size (width x height): {img.size}"

                        )

                         

                        e.g., (800, 600)

                        print

                        (

                        f

                        "Image mode: {img.mode}"

                        )

                         

                        e.g., RGB, RGBA, L (grayscale), etc.

                        Detailed explanation:

                        - `RGB`: color image - `RGBA`: color image with an alpha channel - `L`: grayscale image - `1`: binary image (black and white)

                        2. Resize the image

                        Example

                        Resize the image to 400x300 pixels

                        resized_img

                        =

                        img.

                        resize

                        (

                        (

                        400

                        ,

                        300

                        )

                        )

                        Save the resized image

                        resized_img.

                        save

                        (

                        "output/resized_tiger.jpg"

                        )

                        Detailed explanation:

                        3. Crop the image

                        Example

                        Get the original image size

                        width

                        ,

                        height

                        =

                        img.

                        size

                        Define the crop area (left, top, right, bottom)

                        crop_area

                        =

                        (

                        width//

                        4

                        ,

                        height//

                        4

                        ,

                        3

                        *width//

                        4

                        ,

                        3

                        *height//

                        4

                        )

                         

                        Crop the middle area

                        Perform the crop

                        cropped_img

                        =

                        img.

                        crop

                        (

                        crop_area

                        )

                        Save the cropped image

                        cropped_img.

                        save

                        (

                        "output/cropped_tiger.jpg"

                        )

                        Detailed explanation:

                        - `left`: x-coordinate of the left boundary - `upper`: y-coordinate of the upper boundary - `right`: x-coordinate of the right boundary - `lower`: y-coordinate of the lower boundary

                        4. Rotate the image

                        Example

                        Rotate the image 45 degrees and expand the canvas to show the complete image

                        rotated_img

                        =

                        img.

                        rotate

                        (

                        45

                        ,

                        expand

                        =

                        True

                        )

                        Save the rotated image

                        rotated_img.

                        save

                        (

                        "output/rotated_tiger.jpg"

                        )

                        Detailed explanation:

                        5. Flip the image

                        Example

                        Horizontal flip (left-right mirror)

                        h_flipped

                        =

                        img.

                        transpose

                        (

                        Image.

                        FLIP_LEFT_RIGHT

                        )

                        h_flipped.

                        save

                        (

                        "output/horizontal_flip_tiger.jpg"

                        )

                        Vertical flip (top-bottom mirror)

                        v_flipped

                        =

                        img.

                        transpose

                        (

                        Image.

                        FLIP_TOP_BOTTOM

                        )

                        v_flipped.

                        save

                        (

                        "output/vertical_flip_tiger.jpg"

                        )

                        Detailed explanation:

                        6. Convert color mode

                        Example

                        Convert the image to grayscale

                        grayscale_img

                        =

                        img.

                        convert

                        (

                        'L'

                        )

                        Save the grayscale image

                        grayscale_img.

                        save

                        (

                        "output/grayscale_tiger.jpg"

                        )

                        Detailed explanation:

                        - `'RGB'`: three-channel color - `'RGBA'`: four-channel color (with transparency) - `'CMYK'`: CMYK (four-color printing) mode - `'1'`: binary image (pure black and white)

                        7. Apply image filters

                        Example

                        Apply blur filter

                        blurred_img

                        =

                        img.

                        filter

                        (

                        ImageFilter.

                        BLUR

                        )

                        blurred_img.

                        save

                        (

                        "output/blurred_tiger.jpg"

                        )

                        Apply edge enhancement filter

                        edge_img

                        =

                        img.

                        filter

                        (

                        ImageFilter.

                        EDGE_ENHANCE

                        )

                        edge_img.

                        save

                        (

                        "output/edge_enhanced_tiger.jpg"

                        )

                        Apply contour filter

                        contour_img

                        =

                        img.

                        filter

                        (

                        ImageFilter.

                        CONTOUR

                        )

                        contour_img.

                        save

                        (

                        "output/contour_tiger.jpg"

                        )

                        Detailed explanation:

                        - `ImageFilter.SHARPEN`: sharpen the image - `ImageFilter.EMBOSS`: emboss effect - `ImageFilter.FIND_EDGES`: find edges - `ImageFilter.SMOOTH`: smooth the image

                        8. Adjust image properties (brightness, contrast, sharpness)

                        Example

                        Increase brightness (1.5 means brightness increased by 50%)

                        brightness

                        =

                        ImageEnhance.

                        Brightness

                        (

                        img

                        )

                        bright_img

                        =

                        brightness.

                        enhance

                        (

                        1.5

                        )

                        bright_img.

                        save

                        (

                        "output/brighter_tiger.jpg"

                        )

                        Increase contrast (1.5 means contrast increased by 50%)

                        contrast

                        =

                        ImageEnhance.

                        Contrast

                        (

                        img

                        )

                        contrast_img

                        =

                        contrast.

                        enhance

                        (

                        1.5

                        )

                        contrast_img.

                        save

                        (

                        "output/contrast_tiger.jpg"

                        )

                        Increase sharpness (2.0 means sharpness increased by 100%)

                        sharpness

                        =

                        ImageEnhance.

                        Sharpness

                        (

                        img

                        )

                        sharp_img

                        =

                        sharpness.

                        enhance

                        (

                        2.0

                        )

                        sharp_img.

                        save

                        (

                        "output/sharper_tiger.jpg"

                        )

                        Detailed explanation:

                        - A value of 1.0 means the original image is unchanged - A value greater than 1.0 means an enhanced effect (e.g., 1.5 means a 50% increase) - A value less than 1.0 means a reduced effect (e.g., 0.5 means a 50% decrease)

                        9. Add text to the image

                        Example

                        Create a copy of the image for drawing

                        text_img

                        =

                        img.

                        copy

                        (

                        )

                        Create a drawing object

                        draw

                        =

                        ImageDraw.

                        Draw

                        (

                        text_img

                        )

                        Try loading a font (use the default if unavailable)

                        try

                        :

                           

                        Load a system font with size 36 pixels

                            font

                        =

                        ImageFont.

                        truetype

                        (

                        "arial.ttf"

                        ,

                        36

                        )

                        except

                        IOError

                        :

                           

                        If the specified font is not found, use the default font

                            font

                        =

                        ImageFont.

                        load_default

                        (

                        )

                        Add text on the image

                        draw.

                        text

                        (

                        (

                        10

                        ,

                        10

                        )

                        ,

                        "Tiger"

                        ,

                        fill

                        =

                        (

                        255

                        ,

                        255

                        ,

                        255

                        )

                        ,

                        font

                        =

                        font

                        )

                        Save the image with text added

                        text_img.

                        save

                        (

                        "output/text_tiger.jpg"

                        )

                        Detailed explanation:

                        - The first parameter is the font file path (e.g., "arial.ttf") - The second parameter is the font size (in pixels) - The first parameter `(10, 10)` is the position coordinates of the text (top-left) - The second parameter is the text content to be drawn - The `fill` parameter specifies the text color, here white `(255, 255, 255)` - The `font` parameter specifies the font to use

                        10. Merge Images (Simple Stitching)

                        Example

                        Get the dimensions of the original image

                        width

                        ,

                        height

                        =

                        img.

                        size

                        Create a new blank image with twice the width of the original

                        merged_img

                        =

                        Image.

                        new

                        (

                        'RGB'

                        ,

                        (

                        width*

                        2

                        ,

                        height

                        )

                        )

                        Paste the original image on the left side

                        merged_img.

                        paste

                        (

                        img

                        ,

                        (

                        0

                        ,

                        0

                        )

                        )

                        Convert the grayscale image to RGB and paste it on the right side

                        merged_img.

                        paste

                        (

                        grayscale_img.

                        convert

                        (

                        'RGB'

                        )

                        ,

                        (

                        width

                        ,

                        0

                        )

                        )

                        Save the merged image

                        merged_img.

                        save

                        (

                        "output/merged_tiger.jpg"

                        )

                        Detailed explanation:

                        - The first parameter is the color mode, here `'RGB'` - The second parameter is the image size, here twice the original width and the original height - The first parameter is the image to be pasted - The second parameter is the coordinates of the paste position (top-left)

                        11. Save in Different Formats and Quality

                        Example

                        Save in PNG format (lossless compression)

                        img.

                        save

                        (

                        "output/tiger.png"

                        )

                        Save in BMP format (no compression)

                        img.

                        save

                        (

                        "output/tiger.bmp"

                        )

                        Save as high-quality JPEG (quality 95%)

                        img.

                        save

                        (

                        "output/tiger_high_quality.jpg"

                        ,

                        quality

                        =

                        95

                        )

                        Save as low-quality JPEG (quality 10%)

                        img.

                        save

                        (

                        "output/tiger_low_quality.jpg"

                        ,

                        quality

                        =

                        10

                        )

                        Detailed explanation:

                        - `PNG`: Lossless compression, supports transparency, suitable for icons, screenshots, etc. - `JPEG`: Lossy compression, suitable for photos, does not support transparency - `BMP`: No compression, larger files, but preserves all information - `GIF`: Supports animation, up to 256 colors - The value ranges from 1 (worst quality, smallest file) to 95 (best quality, larger file) - The default value is usually 75

                        12. Create Output Directory

                        Example

                        Ensure the output directory exists

                        output_dir

                        =

                        "output"

                        if

                        not

                        os

                        .

                        path

                        .

                        exists

                        (

                        output_dir

                        )

                        :

                           

                        os

                        .

                        makedirs

                        (

                        output_dir

                        )

                        Detailed explanation: