- 獲取圖片Exif旋轉信息並旋轉圖片
import cv2 from PIL import Image, ExifTags def img_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 image return cv2.warpAffine(image, M, (nW, nH)) def img_rotation_correction(fpath): angle = None cv_img = None try: img = Image.open(fpath) for orientation in ExifTags.TAGS.keys() : if ExifTags.TAGS[orientation]=='Orientation' : break exif=dict(img._getexif().items()) if exif[orientation] == 3 : # 180 angle = 180 elif exif[orientation] == 6 : # 90° angle = 270 elif exif[orientation] == 8 : # -90° angle = 90 except Exception as e: print(f"{e}") else: cv_img = cv2.imread(fpath) cv_img = img_ratation(cv_img, angle) return cv_img
實用筆記系列2
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.