from math import *
import cv2
import random
import numpy as np
def rotate_img_whole_img(img, angle):
'''
img --image
angle --rotation angle
return--rotated img
'''
h, w = img.shape[:2]
rotate_center = (w/2, h/2)
#获取旋转矩阵
# 参数1为旋转中心点;
# 参数2为旋转角度,正值-逆时针旋转;负值-顺时针旋转
# 参数3为各向同性的比例因子,1.0原图,2.0变成原来的2倍,0.5变成原来的0.5倍
M = cv2.getRotationMatrix2D(rotate_center, angle, 1.0)
#计算图像新边界
new_w = int(h * np.abs(M[0, 1]) + w * np.abs(M[0, 0]))
new_h = int(h * np.abs(M[0, 0]) + w * np.abs(M[0, 1]))
#调整旋转矩阵以考虑平移
M[0, 2] += (new_w - w) / 2
M[1, 2] += (new_h - h) / 2
rotated_img = cv2.warpAffine(img, M, (new_w, new_h))
return rotated_img
def rotate_img_ori_img(img):
'''
img --image
angle --rotation angle
return--rotated img
'''
sample_angle =[-10,-7,-5,-2,2,5,7,10]
angle = random.sample(sample_angle,k=1)[-1]
h, w = img.shape[:2]
(h, w) = img.shape[:2]
# 计算旋转中心点
center = (w / 2, h / 2)
# 计算旋转矩阵
M = cv2.getRotationMatrix2D(center, angle, 1.0)
# 进行图像旋转
rotated = cv2.warpAffine(img, M, (w, h))
return rotated
img = cv2.imread("image/test.png")
rotate = rotate_img_ori_img(img)
cv2.namedWindow('window', cv2.WINDOW_NORMAL)
cv2.resizeWindow('window', 800, 600)
cv2.namedWindow('window1', cv2.WINDOW_NORMAL)
cv2.resizeWindow('window1', 800, 600)
cv2.imshow('window', img)
cv2.imshow('window1', rotate)
cv2.waitKey(0)
cv2.destroyAllWindows()
翻译
搜索
复制