OpenCV 和 PIL 图像大小不匹配

OpenCV and PIL image size mismatch

我发现了一个非常奇怪的 jpeg 文件。 (b.jpg)

根据您使用的库(PIL 或 opencv),此图像有不同的大小。

对比图(正常图),我制作了a.jpg。

以下代码说明两个库return大小不同!

这有什么问题 b.jpg ??

import cv2
from PIL import Image
a_path = "a.jpg"
b_path = "b.jpg"
PIL_a = Image.open(a_path)
CV2_a = cv2.imread(a_path)
PIL_b = Image.open(b_path)
CV2_b = cv2.imread(b_path)

PIL_a.size  # width, height
>> (235, 149)
CV2_a.shape[1], CV2_a.shape[0]  # width, height
>> (235, 149)

PIL_b.size  # width, height
>> (5312, 2988)
CV2_b.shape[1], CV2_b.shape[0]  # width, height
>> (2988, 5312)   <-- strange

a.jpg :

b.jpg :

原因是 EXIF orientation tag

  • OpenCV cv2.imread 方法查找方向标签,rotates/flips 相应地查找图像。
  • Image.open 没有寻找方向标签 - 你可以解决它 programmatically.

这是一个重现您案例的代码示例(您需要 ExifTool 才能执行):

import numpy as np
import cv2
from PIL import Image
import subprocess as sp
import shlex

# Build synthetic image
img = np.full((100, 300, 3), 60, np.uint8)
cv2.putText(img, '1', (130, 70), cv2.FONT_HERSHEY_DUPLEX, 2, (255, 30, 30), 4)  # Blue number

cv2.imwrite('image.jpg', img)

# Change the orientation by setting "orientation" exif tag:
# https://superuser.com/questions/435443/how-can-i-modify-the-exif-orientation-tag-of-an-image
sp.run(shlex.split('exiftool -orientation=5 -n image.jpg'))  # Mark image as rotated.

cv_img = cv2.imread('image.jpg')
print((cv_img.shape[1], cv_img.shape[0]))  # (100, 300)

pil_img = Image.open('image.jpg')
print(pil_img.size)  # (300, 100)
pil_img.show()

cv2.imshow('cv_img', cv_img)
cv2.waitKey()
cv2.destroyAllWindows()

pil_img.show():

cv2.imshow('cv_img', cv_img):