0

I am reading image using OpenCV and python.

img=cv2.imread('orig.jpg')

and after modifying the image, I save it again.

cv2.imwrite('modi.jpg', img)

But now its EXIF data is lost.

How can I copy EXIF from orig.jpg to 'modi.jpg'.

I tried EXIF 1.3.5

with open('orig.jpg', 'rb') as img_file:
     img1 = Image(img_file)

with open('modi.jpg', 'wb') as new_image_file:
       new_image_file.write(img1.get_file())

But it overwrites the image data of modi.jpg also.

Shahgee
  • 3,303
  • 8
  • 49
  • 81

1 Answers1

0

EDIT: If you simply want to copy EXIF from one image to another, an easy was might be this

from PIL import Image
# load old image and extract EXIF
image = Image.open('orig.jpg')
exif = image.info['exif']

# load new image
image_new = Image.open('modi.jpg')
image_new.save('modi_w_EXIF.jpg', 'JPEG', exif=exif)

I found this example amongst others here. I noticed this method copied the image thumbnail (not the image information!) to the new file. You might want to set the thumbnail anew.

Another example from the same page seems to be even simpler:

import jpeg
jpeg.setExif(jpeg.getExif('orig.jpg'), 'modi.jpg') 

I couldn't install the required module and test it, though, but it might be worth a try.

Concerning the EXIF module:

You overwrite the image because img1 is not just the EXIF data but the entire image. You would have to do the following steps:

  1. load the image containing the EXIF info and get that information
  2. load the new image which lacks that info
  3. overwrite the new image's EXIF
  4. save the new image with EXIF

Something in the likes of:

f_path_1 = "path/to/original/image/with/EXIF.jpg"
f_path_2 = "path/to/new/image/without/EXIF.jpg"
f_path_3 = "same/as/f_path_2/except/for/test/purposes.jpg"

from exif import Image as exIm # I imported it that way bacause PIL also uses "Image"
with open(f_path_1, "rb") as original_image:
     exif_template = exIm(original_image)
if not exif_template.has_exif:
    Warning("No EXIF data found for " + f_path_1)
tags = exif_template.list_all()

with open(f_path_2, "rb") as new_rgb_image:
     exif_new = exIm(new_rgb_image)

for tag in tags:
    try:
        exec("exif_new." + tag + "=exif_template." + tag)
    except:
        pass

with open(f_path_3, "wb") as new_rgb_image:
     new_rgb_image.write(exif_new.get_file())

Note: For some reason EXIF was only able to write some, but not all tags from the original image when I tried it.

Manuel Popp
  • 1,003
  • 1
  • 10
  • 33