原理:图片旋转的原理
代码实现:code
keras中的图片旋转:datagen = ImageDataGenerator(rotation_range = 40)#随机旋转40度
opencv中的旋转:
#不改变图片大小
import cv2
import numpy as np
def rotate(image, angle, center=None, scale=1.0):
# grab the dimensions of the image and then determine the
(h, w) = image.shape[:2]
# 若未指定旋转中心,则将图像中心设为旋转中心
if center is None:
center = (w / 2, h / 2)
# 计算二维旋转的仿射变换矩阵
M = cv2.getRotationMatrix2D(center, angle, scale)
rotated = cv2.warpAffine(image, M, (w, h))
# 返回旋转后的图像
return rotated
src=cv2.imread("lena.png")
print(src.shape)
output_image2=rotate(src, 45)
print(output_image2.shape)
cv2.namedWindow(" image2", cv2.WINDOW_AUTOSIZE)
cv2.imshow(" image2", output_image2)
cv2.waitKey(0)
cv2.destroyAllWindows()
#改变图片大小
import cv2
import numpy as np
def rotate_bound(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))
src=cv2.imread("lena.png")
print(src.shape)
output_image1=rotate_bound(src, 45)
print(output_image1.shape)
cv2.namedWindow(" image1", cv2.WINDOW_AUTOSIZE)
cv2.imshow(" image1", output_image1)
cv2.waitKey(0)
cv2.destroyAllWindows()