tf.keras.utils.load_img()加载旋转图像未正确显示问题咨询
问题解答
这是预期行为,核心原因在于两种工具对图像EXIF旋转元数据的处理逻辑不同:
- IPython(尤其是Jupyter环境中)在显示图像时,会自动读取图像文件的EXIF元数据中的
Orientation字段,并据此应用旋转,所以你看到的是正确旋转后的图像。 tf.keras.utils.load_img()默认仅加载图像的原始像素数据,不会读取和应用EXIF中的旋转信息,因此加载后的图像呈现的是未旋转的原始像素状态。
解决办法
要让加载后的图像保留旋转效果,需要手动处理EXIF中的旋转信息,以下是实现代码:
from PIL import Image, ExifTags from tensorflow.keras.utils import load_img def load_image_with_exif_rotation(img_path): # 用PIL打开图像 img = Image.open(img_path) # 读取并处理EXIF旋转信息 try: exif_data = img._getexif() if exif_data: for tag_id, value in exif_data.items(): tag_name = ExifTags.TAGS.get(tag_id) if tag_name == 'Orientation': # 根据Orientation值应用对应旋转 if value == 3: img = img.rotate(180, expand=True) elif value == 6: img = img.rotate(270, expand=True) elif value == 8: img = img.rotate(90, expand=True) except AttributeError: # 无EXIF数据时跳过处理 pass # 转换为RGB格式(适配tf.keras的常见需求) img = img.convert("RGB") return img # 使用自定义函数加载图像 rotated_img = load_image_with_exif_rotation("你的旋转图像路径.jpg") # 显示图像(此时会呈现正确旋转后的效果) display(rotated_img)
如果需要直接得到可用于模型的tensor:
import tensorflow as tf def load_img_tensor_with_rotation(img_path): img = load_image_with_exif_rotation(img_path) return tf.convert_to_tensor(img, dtype=tf.float32) / 255.0
总结
这不属于操作错误,是工具设计逻辑的差异导致的结果。IPython的显示层自动处理了EXIF旋转,而tf的图像加载工具默认聚焦于像素数据本身,需要手动补充旋转处理逻辑。
内容的提问来源于stack exchange,提问作者RobertJoseph
相关产品推荐
相关产品推荐

