python opencv 批量旋转图像,使 图像内容不改变,并保存

-- coding: utf-8 --

from PIL import Image
import os

import cv2
from math import *
import numpy as np

path_old ='G:'

此路径不能含有中文名称

degrees=[]
for k in range(1,25):
degrees.append(k*15)

for item in os.listdir(path_old):
in_imgpath = path_old + item
out_name = os.path.splitext(item)[0]
print(in_imgpath)

in_img = cv2.imread(in_imgpath)

height, width = in_img.shape[:2]

for degree in degrees:

    # 旋转后的尺寸
    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(in_img, matRotation, (widthNew, heightNew),
                             borderValue=(255, 255, 255))

    cv2.imwrite(path_old + out_name + '_' + str(degree) + '.jpg', imgRotation)

你可能感兴趣的:(python opencv 批量旋转图像,使 图像内容不改变,并保存)