How to add custom metadata to OpenCV/numpy image?

10,216

So, ultimately, you could just facade the 2 file contents (data and metadata) behind your own python class:

import cv 
import pyexiv2

class MyImage():

  _filename = None
  _data = None
  _metadata = None

  def __init__(self,fname):

    _filename = fname
    _data = cv.LoadImage(_filename)
    _metadata = pyexiv2.ImageMetadata(_filename)
    _metadata.read()

  def addMeta(self,key,value):
    _metadata[key] = pyexiv2.ExifTag(key, value)

  def delMeta(self,delkey):
    newdict = {key: value for key, value in some_dict.items()
                if value is not delkey}

  def resize(self,newx,newy):
    tmpimage = cv.CreateMat(newy, newx, cv.CV_8UC3)
    cv.Resize(_data,tmpimage)
    _data = tmpimage
    try: # Set metadata tags to new size if exist!
      _metadata['Exif.Image.XResolution'] = newx
      _metadata['Exif.Image.YResolution'] = newy
    except:
      pass

  def save(self):
    cv.SaveImage(_filename,_data) 
    _metadata.write()
Share:
10,216
Subhamoy S.
Author by

Subhamoy S.

I love, and mostly code in, C++.

Updated on August 02, 2022

Comments

  • Subhamoy S.
    Subhamoy S. almost 2 years

    I have a question.

    I am performing a series of operations (resize, copy, etc.) to some captured images in OpenCV, but I want to set some specific metadata (the attribute names should also be defined by me) to these images, which would survive those operations and can be extracted later on. I am not setting resolution values or any other value that changes after these operations. How can I do this? I heard of pyexiv2, but I have never seen any example involving OpenCV.

    Thanks in advance!

  • Subhamoy S.
    Subhamoy S. about 12 years
    Thank you for such a nice response! The only problem with using a format like ttf or jpg is, I am not saving the images anywhere. They are being grabbed, transfered over a network connection, displayed, and that's all. I tried cv2.imencode() but due to some kind of bug, it does not produce JPEG. The only way is to convert to cvMat and use legacy method cv.EncodeImage(), which would not preserve the metadata any more.
  • timlukins
    timlukins about 12 years
    Ah - I believe I see your problem. Even if you use the PIL Image class fromBuffer() method you can at least create an image in memory even from the OpenCV raw data. However, it seems you can't then create/update new EXIF tags via PIL.ExifTags...:-( See here.