我正在使用PIL
和cv2
软件包加载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 = 765
和height = 1360
,与cv2
方法报告的相同。为什么PIL
给出了错误的图像尺寸?
只有很少的图像会出现问题。我链接的图像就是这样的图像之一。对于其余图像,PIL
和cv2
报告的高度和宽度相同。
答案 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
----------------------------------------