Home > Back-end >  How to extract metadata using PIL.exiftags?
How to extract metadata using PIL.exiftags?

Time:09-27

I've just been following guides that show the same steps to extracting GPS data from an image. Most of them use the following dictionary definition.

[exif definition][1] 
exif = {
    PIL.ExifTags.TAGS[k]: v 
    for k, v in pil_img._getexif().items()
    if k in PIL.ExifTags.TAGS
}

However, I keep getting AttributeError: _getexif and I have no idea how to fix this. I am new to python. I've ensured the image I'm using has GPS information but I still can't access any of the metadata. Here is the full code so far: Note I am using cv2 to practice converting as this will be applicable to my project full code

from PIL import Image
import PIL
import cv2
import numpy as np
from PIL.ExifTags import TAGS
img = cv2.imread("keyboard.png")
convert = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
pil_img = Image.fromarray(convert)

exif = {
    PIL.ExifTags.TAGS[k]: v 
    for k, v in pil_img._getexif().items()
    if k in PIL.ExifTags.TAGS
}

Additionally if I try to call exif like I saw in a tutorial, I get the following error: exif not recognized

exif : The term 'exif' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
  exif
  ~~~~
      CategoryInfo          : ObjectNotFound: (exif:String) [], CommandNotFoundException
      FullyQualifiedErrorId : CommandNotFoundException

CodePudding user response:

This code works for me:

from PIL import Image
from PIL.ExifTags import TAGS


pil_img = Image.open("img.jpg")
exif_info = pil_img._getexif()
exif = {TAGS.get(k, k): v for k, v in exif_info.items()}
print(exif)

Please note:

  • It is unlikely that the EXIF data persists if you read the image with opencv, convert the colour space and reimport the binary image data to PIL.
  • I don't have png images with exif data. This was tested with jpg only.

CodePudding user response:

Your code cannot possibly work with OpenCV in that fashion.

When you do:

img = cv2.imread("keyboard.png")

you get back a Numpy array of just the pixels in your variable img - and that's all, nothing else, no EXIF, no IPTC, no ICC profile, absolutely zero metadata. OpenCV is only interested in computer vision, not cataloguing, indexing, sorting, managing images by where they were taken or when or by whom or what.

You can use PIL to read metadata, or exiftool or its Python bindings - example here.

  • Related