为什么使用 PIL 与 OpenCV 加载时图像的宽度和高度会颠倒?

GAU*_*AVA 5 python opencv numpy image python-imaging-library

我正在使用PILOpenCV包加载图像。使用 加载图像时的高度和宽度与使用 加载图像时的高度和宽度相反。以下是打印使用这两个包加载的图像的高度和宽度的代码。PILcv2

\n
file = \'conceptual_captions/VL-BERT/data/conceptual-captions/val_image/00002725.jpg\'\n# load image using PIL\nimport PIL.Image\npil = PIL.Image.open(file).convert(\'RGB\')\nw, h = pil.size\nprint("width: {}, height: {}".format(w, h))\n
Run Code Online (Sandbox Code Playgroud)\n

打印输出\nwidth: 1360, height: 765

\n
# now using cv2\nimport cv2\nim = cv2.imread(file)\nprint("height, width, channels: {}".format(im.shape)) \n
Run Code Online (Sandbox Code Playgroud)\n

打印输出height, width, channels: (1360, 765, 3)

\n

我下载了图像并使用 Mac 上的信息选项检查了图像的大小。信息有width = 765height =\xe2\x80\x8a1360,与方法报告的相同cv2。为什么PIL给出错误的图像尺寸?

\n

当图像非常少时就会出现此问题。我链接的图像就是这样的一张图像。对于其余图像,PIL和报告的高度和宽度cv2是相同的。

\n

Han*_*rse 12

该图像具有一些 EXIF 元数据,包括有关方向(旋转)的信息。我建议阅读问答以及随后的参考资料。

尽管如此,现在提出的解决方案可以简化,只需使用PIL.ImageOps.exif_transpose()

如果图像具有 EXIF 方向标签,则返回相应转置的新图像。否则,返回图像的副本。

一些要测试的代码:

from PIL import Image, ImageOps

# Read original image, show width and height
file = '...'
pil = Image.open(file).convert('RGB')
w, h = pil.size
print("width: {}, height: {}".format(w, h))

# Transpose with respect to EXIF data
pil = ImageOps.exif_transpose(pil)
w, h = pil.size
print("width: {}, height: {}".format(w, h))
Run Code Online (Sandbox Code Playgroud)

相应的输出:

width: 1360, height: 765
width: 765, height: 1360
Run Code Online (Sandbox Code Playgroud)
----------------------------------------
System information
----------------------------------------
Platform:     Windows-10-10.0.16299-SP0
Python:       3.8.5
Pillow:       7.2.0
----------------------------------------
Run Code Online (Sandbox Code Playgroud)