在python中使用opencv编辑图像时无法保留图像exif数据



我正在尝试在python中裁剪图像,并且在裁剪图像时需要保留exif数据,但是当我保存生成的裁剪图像时,我丢失了原始图像的exif数据,如何避免这种情况发生? 我一直在运行的代码:

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')

当您将图像加载到 OpenCV 中时,由于图像被转换为 NumPy 数组,因此您需要从图像中读取它,然后在保存它之后将其重写为图像。

您可以使用 pyexiv2 执行此操作,此模块可用于此任务。

以下是读取元数据的一些示例:

import pyexiv2
img = pyexiv2.Image(r'.pyexiv2tests1.jpg')
data = img.read_exif()
img.close()

下面是一个修改示例:

# 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()

在这里你可以找到文档

最新更新