背景
许多相机,尤其手机采集的图像会存在镜像的问题,但是如果opencv版本或者解析图像时不注意,就会以为前后端读取图像工具不一样的原因,导致前端与后端或者不同工具间,看似处理的是同一张图像,实则是存在镜像的两张图像。
所以需要规避此问题,应该读取图像时,获取其EXIF信息,如果有则根据情况进行处理。
代码
# 使用函数修复图像方向
image = fix_orientation_with_opencv('path_to_your_image.jpg')
# 保存处理后的图像
cv2.imwrite(save_path, image )
函数实现
import cv2
import numpy as np
from PIL import Image, ImageOps
def fix_orientation_with_opencv(image_path):
# 使用PIL读取图像以获取EXIF信息
pil_image = Image.open(image_path)
exif = pil_image._getexif()
orientation = exif.get(274) if exif else None
# 使用OpenCV读取图像
img = cv2.imread(image_path)
if orientation == 1:
# 正常(图像不需要旋转)
pass
elif orientation == 2:
# 水平翻转(左右镜像)
img = cv2.flip(img, 1)
elif orientation == 3:
# 180度旋转
img = cv2.rotate(img, cv2.ROTATE_180)
elif orientation == 4:
# 垂直翻转(上下镜像)
img = cv2.flip(img, 0)
elif orientation == 5:
# 顺时针旋转90度后水平翻转
img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
img = cv2.flip(img, 1)
elif orientation == 6:
# 顺时针旋转90度
img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
elif orientation == 7:
# 逆时针旋转90度后水平翻转
img = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)
img = cv2.flip(img, 1)
elif orientation == 8:
# 逆时针旋转90度
img = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)
return img