import cv2
from PIL import Image, ExifTags
defimg_ratation(image, angle):"""
"""# grab the dimensions of the image and then determine the# center(h, w)= image.shape[:2](cX, cY)=(w //2, h //2)# grab the rotation matrix (applying the negative of the# angle to rotate clockwise), then grab the sine and cosine# (i.e., the rotation components of the matrix)
M = cv2.getRotationMatrix2D((cX, cY),-angle,1.0)
cos = np.abs(M[0,0])
sin = np.abs(M[0,1])# compute the new bounding dimensions of the image
nW =int((h * sin)+(w * cos))
nH =int((h * cos)+(w * sin))# adjust the rotation matrix to take into account translation
M[0,2]+=(nW /2)- cX
M[1,2]+=(nH /2)- cY
# perform the actual rotation and return the imagereturn cv2.warpAffine(image, M,(nW, nH))defimg_rotation_correction(fpath):"""
获取文件的旋转角度信息并矫正
"""
angle =0
cv_img =Nonetry:
img = Image.open(fpath)
detect_orientation_info =Falsefor orientation in ExifTags.TAGS.keys():if ExifTags.TAGS[orientation]=='Orientation':
detect_orientation_info=Truebreakif detect_orientation_info and img._getexif():
exif=dict(img._getexif().items())if exif[orientation]==3:# 180
angle =180elif exif[orientation]==6:# 顺时针90°
angle =270elif exif[orientation]==8:# 逆时针90°
angle =90except Exception as e:print(f"correct error:{e}")finally:
cv_img = cv2.imread(fpath)if angle:
cv_img = img_ratation(cv_img, angle)return cv_img
获取图片Exif旋转信息并旋转图片import cv2from PIL import Image, ExifTagsdef img_ratation(image, angle): # grab the dimensions of the image and then determine the # center (h, w) = image.shape[:2] ...