我在尝试从数据集中的图像中移除EXIF数据(这些数据将用于迁移学习)。然而,这似乎不起作用。以下是我的代码:
我尝试使用PIL保存图像(按照之前提问的方式:Python: 从图像中移除Exif信息),但输出完全是由”except”组成。
我又尝试使用piexif模块,如下所示:
# 与上述相同的导入Folder = 'drive/My Drive/PetImages'labels =['Dog', 'Cat']for label in labels: imageFolder = os.path.join(Folder, label) listImages = os.listdir(imageFolder) for img in tqdm(listImages): imgPath = os.path.join(imageFolder,img) try: ImageType = img.format # warnings.filterwarnings("error") if ImageType in ["JPEG", "TIF", "WAV"]: exif_data = img._getexif() print(exif_data) piexif.remove(img) print("done") except: print("except")
在上面的代码中,我首先检查图像类型,以确保方法_getexif()确实存在,然后在保存到exif_data变量后移除数据。输出包括”except”和偶尔的exif数据(以字典形式)或”None”(如果不存在),但从未出现过”done”字样。为什么它没有到达那部分呢?
回答:
对于通过Google找到这篇文章的任何人,这里有一个使用PIL的简单解决方案:
from PIL import Imageim = Image.open('some-image.jpg')# 这将清除所有exif数据im.getexif().clear()im.save('some-image-without-exif.jpg')
我原以为getexif()
仅允许读取访问,因为名称可能暗示了这一点,但事实证明并非如此。
编辑:在我这里,仅仅加载和保存文件就有效了,不需要im.getexif().clear()
。不过,我不知道这种方法有多可靠。那个命令确实从图像对象中移除了exif数据。这可以在Python shell中简单测试:
>>> from PIL import Image>>> im = Image.open('some-image.jpg')>>> print(im.getexif()){296: 2, 282: 72.0, 283: 72.0 ..... }>>> im.getexif().clear()>>> print(im.getexif()){}