首页 > 解决方案 > 有没有办法在使用 PIL 加载图像时忽略 EXIF 方向数据?

问题描述

使用 PIL 加载图像时,我得到了一些不需要的旋转。我正在加载图像样本及其二进制掩码,所以这会导致问题。我正在尝试将代码转换为使用 openCV,但事实证明这很棘手。我在 Image.load() 下的文档中没有看到任何参数,但我希望有一个我还没有找到的解决方法......

标签: python-3.xopencvpython-imaging-library

解决方案


有,但我没有写完。基本上,如果您加载设置了EXIF “方向”字段的图像,您可以获得该参数。

首先,使用 PIL GitHub 源代码中的此图像进行快速测试Pillow-7.1.2/Tests/images/hopper_orientation_6.jpg 并在其上运行jhead,您可以看到 EXIF 方向为 6:

jhead /Users/mark/StackOverflow/PillowBuild/Pillow-7.1.2/Tests/images/hopper_orientation_6.jpg
File name    : /Users/mark/StackOverflow/PillowBuild/Pillow-7.1.2/Tests/images/hopper_orientation_6.jpg
File size    : 4951 bytes
File date    : 2020:04:24 14:00:09
Resolution   : 128 x 128
Orientation  : rotate 90     <--- see here
JPEG Quality : 75

现在在 PIL 中执行此操作:

from PIL import Image

# Load that image
im = Image.open('/Users/mark/StackOverflow/PillowBuild/Pillow-7.1.2/Tests/images/hopper_orientation_6.jpg')                         

# Get all EXIF data
e = im.getexif()

# Specifically get orientation
e.get(0x0112)                                                                                                                       
# prints 6

现在单击,您可以计算出图像如何旋转并撤消它。


或者,您可能完全不专业 ;-) 并创建一个名为的函数,并使用以下命令将其SneakilyRemoveOrientationWhileNooneIsLooking(filename)取出(子进程)exiftool并删除方向:

exiftool -Orientation=  image.jpg

推荐阅读