How to Extract Image Metadata in Python?

Posted in /  

How to Extract Image Metadata in Python?
vinaykhatri

Vinay Khatri
Last updated on November 21, 2024

    This article details how to extract image metadata in Python. When we take an image using a digital camera, or a smartphone, the camera uses the Exchangeable Image File Format (EXIF) standards to store the image. The EXIF standards use metatags to specify the information about the image.

    If you want to access that metadata for the EXIF standard images in Python, then you need to use an image handling Python library. To handle images in Python, we generally use the most popular Python image handling library, Pillow.

    Here in this Python tutorial, we will walk you through a Python program that will extract useful metadata from a digital image, but before getting started with the Python program, let's install the required libraries.

    Installing Dependencies

    1) The Python pillow Library

    Pillow is the de-facto Python image handling library, and many Python image processing and machine learning libraries are built on top of it. To install pillow for your Python environment, run the following pip install command on your command prompt (Windows) or terminal (Linux and macOS):

    pip install Pillow

    2) The Python prettytable Library

    prettytable is an open-source Python library that is used to print data in a tabular format. We will be using this library in this tutorial to print all the metadata information in a tabular format. To install the prettytable library for your Python environment, use the following pip install command:

    pip install prettytable

    For this tutorial, we will be using the following image image.jpg that we have clicked with a smartphone:

    How to Extract Image Metadata in Python?

    Start with launching your best Python IDE or text editor and start with importing the required modules from the Pillow and prettytable libraries.

    #load modules
    from PIL import Image
    from PIL.ExifTags import TAGS
    from prettytable import PrettyTable

    Next, set a Python identifier image_filename that will hold the file name of the image, and also initialize the prettytable library's PrettyTable() module object and set its fields.

    image_filename = "image.jpg"
    
    #initialiting prettytable object
    table = PrettyTable()
    
    #setting table feilds name
    table.field_names = ["MetaTags", "Values"]

    Now, load the image in a Python script using the Image module.

    #load image
    my_image = Image.open(image_filename)
    Next, let's get the EXIF data of the loaded image using the getexif() method.
    
    #get EXIF standard Data of the image
    img_exif_data = my_image.getexif()

    The getexif() method only returns the tags IDs and their values, and not the tag names. That's why we have also imported the PIL.ExifTags tags that can retrieve the EXIF tag name based on its ID. Now we will loop through the IDs present in img_exif_data and get their tag names using the TAGS.get() method and values using the img_exif_data.get() method.

    for id  in img_exif_data:
        tag_name = TAGS.get(id, id)
        data = img_exif_data.get(id)
        
        #if data in bytes
        if isinstance(data, bytes):
            data = data.decode()
        #add tag name and data into table
        table.add_row([tag_name, data])
    
    #display data
    print(table)

    Some of the EXIF data is present in the binary format (bytes), and that's why we have decoded it into a human-readable format using the data.decode() method. Now, it's time to put all the code together and execute it.

    #Python Program to Extract Metadata from an Image File.

    #load modules
    from PIL import Image
    from PIL.ExifTags import TAGS
    from prettytable import PrettyTable
    
    image_filename = "image.jpg"
    
    #initialiting prettytable object
    table = PrettyTable()
    
    #setting table feilds name
    table.field_names = ["MetaTags", "Values"]
    
    #load image
    my_image = Image.open(image_filename)
    
    #get EXIF standared Data of the image
    img_exif_data = my_image.getexif()
    
    for id  in img_exif_data:
        tag_name = TAGS.get(id, id)
        data = img_exif_data.get(id)
        
        #if data in bytes
        if isinstance(data, bytes):
            data = data.decode()
    
        table.add_row([tag_name, data])
    
    print(table)

    Output

    +----------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    |          MetaTags          |                                                                                Values                                                                                |
    +----------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    |        ExifVersion         |                                                                                 0220                                                                                 |
    |  ComponentsConfiguration   |                                                                                                                                                                      |
    |     ShutterSpeedValue      |                                                                                9.965                                                                                 |
    |      DateTimeOriginal      |                                                                         2020:08:19 10:49:13                                                                          |
    |     DateTimeDigitized      |                                                                         2020:08:19 10:49:13                                                                          |
    |       ApertureValue        |                                                                                 1.44                                                                                 |
    |      BrightnessValue       |                                                                                 5.5                                                                                  |
    |     ExposureBiasValue      |                                                                                 nan                                                                                  |
    |      MaxApertureValue      |                                                                                 1.44                                                                                 |
    |        MeteringMode        |                                                                                  2                                                                                   |
    |        LightSource         |                                                                                  21                                                                                  |
    |           Flash            |                                                                                  16                                                                                  |
    |        FocalLength         |                                                                                4.755                                                                                 |
    |         ColorSpace         |                                                                                  1                                                                                   |
    |       ExifImageWidth       |                                                                                 8000                                                                                 |
    |      SceneCaptureType      |                                                                                  0                                                                                   |
    |         SubsecTime         |                                                                                750682                                                                                |
    |     SubsecTimeOriginal     |                                                                                750682                                                                                |
    |    SubsecTimeDigitized     |                                                                                750682                                                                                |
    |      ExifImageHeight       |                                                                                 6000                                                                                 |
    |        ImageLength         |                                                                                 6000                                                                                 |
    |            Make            |                                                                               OnePlus                                                                                |
    |           Model            |                                                                                HD1901                                                                                |
    |       SensingMethod        |                                                                                  1                                                                                   |
    |        Orientation         |                                                                                  1                                                                                   |
    |      YCbCrPositioning      |                                                                                  1                                                                                   |
    |        ExposureTime        |                                                                                0.001                                                                                 |
    | ExifInteroperabilityOffset |                                                                                 791                                                                                  |
    |        XResolution         |                                                                                 72.0                                                                                 |
    |          FNumber           |                                                                                 1.65                                                                                 |
    |         SceneType          |                                                                                                                                                                      |
    |        YResolution         |                                                                                 72.0                                                                                 |
    |      ExposureProgram       |                                                                                  1                                                                                   |
    |          GPSInfo           | {1: 'N', 2: (29.0, 52.0, 46.6535), 3: 'E', 4: (79.0, 20.0, 54.5711), 5: b'\x00', 6: 0.0, 7: (5.0, 19.0, 13.0), 27: b'ASCII\x00\x00\x00CELLID\x00', 29: '2020:08:19'} |
    |      ISOSpeedRatings       |                                                                                 200                                                                                  |
    |       ResolutionUnit       |                                                                                  2                                                                                   |
    |        ExposureMode        |                                                                                  1                                                                                   |
    |      FlashPixVersion       |                                                                                 0100                                                                                 |
    |         ImageWidth         |                                                                                 8000                                                                                 |
    |        WhiteBalance        |                                                                                  0                                                                                   |
    |          DateTime          |                                                                         2020:08:19 10:49:13                                                                          |
    |   FocalLengthIn35mmFilm    |                                                                                  27                                                                                  |
    |         ExifOffset         |                                                                                 210                                                                                  |
    |         MakerNote          |                                                                                   MM *                                                                                                                                             |
    +----------------------------+------------------------------------------------------------------------------------------------------------------------------------------

    From the output, you can see that the program prints all the metadata about the image. It also displays the GPS coordinates where the image had been clicked.

    Conclusion

    In this Python tutorial, you learned how to extract image metadata in Python. Metadata contains all the information based on the EXIF Standards. We would suggest you use an image captured using a smartphone when you are extracting the EXIF metadata information.

    You can also extract the geolocation coordinates from the image and write a Python program to find the physical address of the clicked image.

    People are also reading:

    Leave a Comment on this Post

    0 Comments