在使用PIL和cv2进行加载时,为什么图像的宽度和高度会颠倒?

时间:2020-09-18 01:07:21

标签: python image python-imaging-library cv2 dimensions

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

file = 'conceptual_captions/VL-BERT/data/conceptual-captions/val_image/00002725.jpg'
# load image using PIL
import PIL.Image
pil = PIL.Image.open(file).convert('RGB')
w, h = pil.size
print("width: {}, height: {}".format(w, h))

打印输出 width: 1360, height: 765

# now using cv2
import cv2
im = cv2.imread(file)
print("height, width, channels: {}".format(im.shape)) 

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

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

只有很少的图像会出现问题。我链接的图像就是这样的图像之一。对于其余图像,PILcv2报告的高度和宽度相同。

1 个答案:

答案 0 :(得分:3)

图像具有一些EXIF元数据,其中包括有关方向(旋转)的信息。我建议在那里阅读this问答和后续参考。

尽管如此,现在可以简化提议的解决方案,只需使用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))

相应的输出:

width: 1360, height: 765
width: 765, height: 1360
----------------------------------------
System information
----------------------------------------
Platform:     Windows-10-10.0.16299-SP0
Python:       3.8.5
Pillow:       7.2.0
----------------------------------------