使用 alpha 通道和 EXIF 旋转读取图像

Read an image with the alpha channel and EXIF rotation

我正在使用 OpenCV 读取 Python 中的 PNG 图像。我需要以 RGBA 格式读取图像并遵守可能的 EXIF 标志,例如图像旋转。

当我尝试通过 cv2.imread("path", cv2.IMREAD_UNCHANGED) 读取图像时,EXIF 标志被忽略(根据文档)。

当我尝试通过 cv2.imread("path", cv2.IMREAD_ANYCOLOR) 读取图像时,alpha 通道被删除。

有没有办法两者兼得?我应该使用另一个库(如 PIL)吗?

我最终使用 PIL 并手动旋转 EXIF 数据中的图像。这是一个有助于处理旋转的片段:

import cv2

import numpy as np

from PIL import Image

_EXIF_ORIENTATION_FLAG_ID = 0x112

_EXIF_ORIENTATION_2_OPENCV_ROTATION = {

    3: cv2.ROTATE_180,

    6: cv2.ROTATE_90_CLOCKWISE,

    8: cv2.ROTATE_90_COUNTERCLOCKWISE

}


# ...

with Image.open(path) as pil_image:

    pixels = np.array(pil_image)

    exif = pil_image.getexif()

if exif is not None and _EXIF_ORIENTATION_FLAG_ID in exif:

    orientation = exif.get(_EXIF_ORIENTATION_FLAG_ID)

    if orientation is not None and orientation != 1:

        pixels = cv2.rotate(pixels, EXIF_ORIENTATION_2_OPENCV_ROTATION[orientation])