A lot of web applications and web services these days use EXIF data in images to handle and process them accordingly. However, extracting the EXIF data from an image is not a simple task and there are a lot of formats and data sets that one needs to deal with. Here is a blog that looks at some of the widely used methods on how one can go about Extract EXIF Data from an Image using Python.
What is EXIF data?
EXIF data is a form of metadata that is embedded in many digital images. It contains a variety of information about the image, such as the date and time it was taken, the camera settings that were used, and the GPS coordinates of the location where the image was taken. This information can be very useful when trying to track down the source of an image, or when trying to determine the context in which it was taken.
Method 1: using pil library
Prerequisites:
PIL: The Pil library is a Python library that enables the user to create, manipulate and convert images. The library is based on the Pillow library and provides a range of image processing and manipulation functions. The library is written in C and is available for Windows, Linux, and macOS.
pip install pil
Code:
Import all the dependencies
from PIL import Image
from PIL.ExifTags import TAGS
Here we are adding the path of the image and then opening that image with pil.
Note: This method only works on jpg files so use that only.
imagename = 'photo2.jpg'
image = Image.open(imagename)
Before taking the EXIF data from an image, we should first try to gain some knowledge about it. To do that, we can use the pillow library to discover some attributes of the image object. Let’s print them out first.
# getting the basic metadata from the image
info_dict = {
"Filename": image.filename,
"Image Size": image.size,
"Image Height": image.height,
"Image Width": image.width,
"Image Format": image.format,
"Image Mode": image.mode,
"Image is Animated": getattr(image, "is_animated", False),
"Frames in Image": getattr(image, "n_frames", 1)
}
for label,value in info_dict.items():
print(f"{label:25}: {value}")
Output:
Now let’s Extract EXIF Data from an Image using Python and getexif() function.
exifdata = image.getexif()
The problem is that the EXIF data variable just returns field names as integers instead of a human-readable values. We will need to use the data within our image data table to grab the correct field names for our project.
# iterating over all EXIF data fields
for tag_id in exifdata:
tag = TAGS.get(tag_id, tag_id)
data = exifdata.get(tag_id)
# decode bytes
if isinstance(data, bytes):
data = data.decode()
print(f"{tag:25}: {data}")
Output:
Here you can see a list of info about the image like the model, software, date and time the image is taken, etc.
Method 2: using EXIF library
Prerequisites:
EXIF: The EXIF library for python is a great tool to extract EXIF Data from an Image using Python. With this library, you can easily get access to all of the metadata associated with a photo, including the date and time it was taken, the camera settings used, and the location of the photo. This information can be very useful when trying to organize and manage your digital photos. To install the EXIF library use the following command:
pip install exif
Code:
First, let’s open the image in the EXIF library
from exif import Image
img_path = 'random2.jpg'
with open(img_path, 'rb') as src:
img = Image(src)
print (src.name, img)
Output:
Now that we loaded our image, let’s see what contains EXIF data in our image.
print(img.list_all())
Output:
So as you can see we have lots of EXIF data in the particular image. For example, let’s extract the date and time of the image using the get method.
print(f' Date and Time: {img.get("datetime")}')
Output:
Extract the location of the image:
To extract the location of the image first we need to extract the longitude and latitude and reference of the image.
from exif import Image
img_path = 'random2.jpg'
with open(img_path, 'rb') as src:
img = Image(src)
# getting the Longitude and latitude data
print(f' Longitude data: {img.get("gps_longitude")}')
print(f' latitude data: {img.get("gps_latitude")}')
# getting the Longitude and latitude Reference data is also very important when converting the Decimal degrees formen
print(f' Longitude data reference : {img.get("gps_longitude_ref")}')
print(f' latitude data reference : {img.get("gps_latitude_ref")}')
Output:
This data is currently in Degrees, minutes, and seconds (DMS) format so we need to convert the data into decimal degree (DD) format.
from exif import Image
img_path = 'random2.jpg'
with open(img_path, 'rb') as src:
img = Image(src)
def decimal_coords(coords, ref):
decimal_degrees = coords[0] + \
coords[1] / 60 + \
coords[2] / 3600
if ref == "S" or ref == "W":
decimal_degrees = -decimal_degrees
return decimal_degrees
def image_coordinates(image_path):
with open(img_path, 'rb') as src:
img = Image(src)
if img.has_exif:
try:
img.gps_longitude
coords = (decimal_coords(img.gps_latitude,
img.gps_latitude_ref),
decimal_coords(img.gps_longitude,
img.gps_longitude_ref))
except AttributeError:
print('No Coordinates')
else:
print('The Image has no EXIF information')
print(f"Image {src.name}, OS Version:{img.get('software', 'Not Known')} ------")
print(f"Was taken: {img.datetime_original}, and has coordinates:{coords}")
image_coordinates(img_path)
Let’s look at the code explanation:
- Import the dependency
- Loaded the image into the EXIF module
- Created a function to convert the coordinates into Decimal degrees (DD) format.
- Then created another function to print out the coordinates in Decimal degrees (DD) format with some additional metadata of the image.
Output:
And that’s it now we have our coordinates in decimal degree format and if you want to use them just copy and paste them into google maps.
Final Words
In this blog post, we explored two different methods of extracting your EXIF data. Firstly use the Python Imaging Library, it’s a great tool but can only extract certain types of information. The second method was using the EXIF library, which is quite advanced and has a lot more options compared to the pil library. The EXIF library data also contain the location coordinates of the picture which is great for any type of geo-analysis or simply mapping the location where the image was taken. Hope you like the blog, If you have any further questions, please don’t hesitate to contact us. Thank you for reading!
Related Articles
- Concurrency in Python
- Basic Neural Network in Python to Make Predictions
- Monitor Python scripts using Prometheus
- How to Implement Google Login in Flask App
- How to create a Word Guessing Game in Python
- Convert an image to 8-bit image
- Schedule Python Scripts with Apache Airflow
- Create Sudoku game in Python using Pygame
- How to Deploy Flask API on Heroku?
- Create APIs using gRPC in Python