我正在使用 OpenCV 和 python 读取图像。
img=cv2.imread('orig.jpg')
修改图像后,我再次保存它。
cv2.imwrite('modi.jpg', img)
但是现在它的EXIF数据丢失了。
如何将 EXIF 从 orig.jpg 复制到
'modi.jpg'
。
我尝试过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())
但它也会覆盖
modi.jpg
的图像数据。
编辑:如果您只是想将 EXIF 从一张图像复制到另一张图像,一个简单的方法可能就是这样
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)
我在其他这里找到了这个例子。我注意到这种方法将图像缩略图(而不是图像信息!)复制到新文件中。您可能想重新设置缩略图。
同一页面的另一个示例似乎更简单:
import jpeg
jpeg.setExif(jpeg.getExif('orig.jpg'), 'modi.jpg')
虽然我无法安装所需的模块并进行测试,但它可能值得一试。
关于
EXIF
模块:
您覆盖了图像,因为
img1
不只是 EXIF 数据,而是整个图像。您必须执行以下步骤:
类似以下内容:
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())
注意:由于某种原因,当我尝试时,
EXIF
只能写出原始图像中的一些标签,但不能写出所有标签。
关于Manuel Popp之前提到的网上的一个方法:
"""
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)
"""
此方法在 Python 3 中的 PIL 9.4.0 下不再有效。 手动 Popp 的最终答案将会起作用。