一、利用PIL
import PIL
from PIL import Image
def rotate_1(inputpath, outputpath, value):
'''
说明 :将图片旋转任意角度值
picin : 输入图片路径
picout : 输出图片路径
value : 角度值
'''
im1 = PIL.Image.open(inputpath) # 打开图片路径1
# 旋转value角度
im2 = im1.rotate(270 + eval(str(value)))
# im2.show()
im2.save(outputpath) # 保存路径
二、利用opencv
import cv2
import numpy as np
from math import *
def rotate(picin, picout, value):
'''
说明 :将图片旋转任意角度值
picin : 输入图片路径
picout : 输出图片路径
value : 角度值
'''
# img = cv2.imread("plane.jpg")
img = Image.open(picin)
img = np.array(img)
height, width = img.shape[:2]
degree = 270 + value
# 旋转后的尺寸
heightNew = int(width * fabs(sin(radians(degree))) + height * fabs(cos(radians(degree))))
widthNew = int(height * fabs(sin(radians(degree))) + width * fabs(cos(radians(degree))))
matRotation = cv2.getRotationMatrix2D((width / 2, height / 2), degree, 1)
matRotation[0, 2] += (widthNew - width) / 2 # 重点在这步
matRotation[1, 2] += (heightNew - height) / 2 # 重点在这步
imgRotation = cv2.warpAffine(img, matRotation, (widthNew, heightNew), borderValue=(255, 255, 255))
cv2.imwrite(picout, imgRotation)