2

I'm trying to crop images in python, and need keep the exif data when I crop them, but I lose the exif data of the original image when I save the resulting cropped image, how can I avoid this from happening? The code I've been running:

from imutils import face_utils
import imutils
import numpy as np
import collections
import dlib
import cv2
import glob
import os

detector = dlib.get_frontal_face_detector()
PREDICTOR_PATH = "shape_predictor_68_face_landmarks.dat"
predictor = dlib.shape_predictor(PREDICTOR_PATH)

def face_remap(shape):
    remapped_image = cv2.convexHull(shape)
    return remapped_image


def faceCrop(imagePattern):

    imgList=glob.glob(imagePattern)
    if len(imgList)<=0:
        print ('No Images Found')
        return
    for img in imgList:
        image = cv2.imread(img)
        image = imutils.resize(image, width=500)
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        out_face = np.zeros_like(image)
        rects = detector(gray, 1)
        for (i, rect) in enumerate(rects):
            shape = predictor(gray, rect)
            shape = face_utils.shape_to_np(shape)
            #initialize mask array
            remapped_shape = np.zeros_like(shape) 
            feature_mask = np.zeros((image.shape[0], image.shape[1]))   
            # we extract the face
            remapped_shape = face_remap(shape)
            cv2.fillConvexPoly(feature_mask, remapped_shape[0:27], 1)
            feature_mask = feature_mask.astype(np.bool)
            out_face[feature_mask] = image[feature_mask]
            fname,ext=os.path.splitext(img)
            cv2.imwrite(fname+'_crop'+ext, out_face)
    print ('Listo \n')                
faceCrop('/Users/alejandroramirez/Documents/imagenes nuevas/2/*.JPG')

1 Answers1

0

When you load an image into OpenCV you lost all the metadata due to the fact that the image is converted into a NumPy array, so you need to read it from the image and then rewrite it to the image after that you saved it.

You can do this with pyexiv2 this module can be used for this task.

here some example of reading of metadata:

import pyexiv2
img = pyexiv2.Image(r'.\pyexiv2\tests\1.jpg')
data = img.read_exif()
img.close()

here an example of modify:

# Prepare the XMP data you want to modify
dict1 = {'Xmp.xmp.CreateDate': '2019-06-23T19:45:17.834',   # Assign a value to a tag. This will overwrite its original value, or add it if it doesn't exist
...          'Xmp.xmp.Rating': None}                            # Assign None to delete the tag
img.modify_xmp(dict1)
dict2 = img.read_xmp()       # Check the result
dict2['Xmp.xmp.CreateDate']
'2019-06-23T19:45:17.834'        # This tag has been modified
dict2['Xmp.xmp.Rating']
KeyError: 'Xmp.xmp.Rating'       # This tag has been deleted
img.close()

here you can find the docs

SvMax
  • 157
  • 2
  • 10