Open In App

How to extract image metadata in Python?

Prerequisites: PIL

Metadata stands for data about data. In case of images, metadata means details about the image and its production. Some metadata is generated automatically by the capturing device. 



Some details contained by image metadata is as follows:

Python has PIL library which makes the task of extracting metadata from an image extremely easy that too by using just a few lines.



Approach:

There are many types of metadata but in this we are only focusing on Exif metadata

Using Exif to extract image metadata

These metadata, often created by cameras and other capture devices, include technical information about an image and its capture method, such as exposure settings, capture time, GPS location information and camera model.

for this i have used this picture(link for this is below) make sure whatever picture you are using it  should have some metadata of EXIF type and most of the capturing devices have exif data

https://drive.google.com/file/d/1z2RaRvzC8Cd8oxD8pZJu2U0rpRr8tbwV/view 

NOTE:-please avoid the image shared through whatsapp. Whatsapp strips away all metadata from any image 

Implementation:

Application to extract Metadata from a image with pillow : below script implements the above approach




from PIL import Image
from PIL.ExifTags import TAGS
 
# open the image
image = Image.open("img.jpg")
 
# extracting the exif metadata
exifdata = image.getexif()
 
# looping through all the tags present in exifdata
for tagid in exifdata:
     
    # getting the tag name instead of tag id
    tagname = TAGS.get(tagid, tagid)
 
    # passing the tagid to get its respective value
    value = exifdata.get(tagid)
   
    # printing the final result
    print(f"{tagname:25}: {value}")

Output:

 

Using subprocess to extract image metadata

Here we are using the subprocess module to extract image metadata using popen() method which opens a pipe from a command. And this pipe allows the command to send its output to another command. And we are storing the fetched metadata into a dictionary.




import subprocess
 
imgPath = "C:\\Users\\DELL\\Downloads\\output.jpg"
exeProcess = "hachoir-metadata"
process = subprocess.Popen([exeProcess,imgPath],
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT,
                           universal_newlines=True)
Dic={}
 
for tag in process.stdout:
        line = tag.strip().split(':')
        Dic[line[0].strip()] = line[-1].strip()
 
for k,v in Dic.items():
    print(k,':', v)

Output:

 


Article Tags :