使用opencv函数的转置操作+翻转操作实现旋转
使用numpy.rot90实现
def rotateAntiClockWise90(img_file): # 顺时针旋转90度
img = cv2.imread(img_file)
trans_img = cv2.transpose(img)
img90 = cv2.flip(trans_img, 0)
cv2.imshow("rotate", img90)
cv2.waitKey(0)
return img90
def totateAntiClockWise90ByNumpy(img_file): # np.rot90(img, -1) 顺时针旋转90度 旋转程度:1,2,-1,-2
img = cv2.imread(img_file)
img90 = np.rot90(img, -1)
cv2.imshow("rotate", img90)
cv2.waitKey(0)
return img90
旋转180度、270度
使用numpy.rot90实现旋转180度、270度
img180 = np.rot90(img, 2)
cv2.imshow("rotate", img180)
cv2.waitKey(0)
旋转任意角度,以任意色值填充背景
import cv2
from math import *
import numpy as np
# 旋转angle角度,缺失背景白色(255, 255, 255)填充
def rotate_bound_white_bg(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)
# -angle位置参数为角度参数负值表示顺时针旋转; 1.0位置参数scale是调整尺寸比例(图像缩放参数),建议0.75
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
# borderValue 缺失背景填充色彩,此处为白色,可自定义
return cv2.warpAffine(image, M, (nW, nH),borderValue=(255,255,255))
# borderValue 缺省,默认是黑色(0, 0 , 0)
# return cv2.warpAffine(image, M, (nW, nH))
img = cv2.imread("dog.png")
imgRotation = rotate_bound_white_bg(img, 45)
cv2.imshow("img",img)
cv2.imshow("imgRotation",imgRotation)
cv2.waitKey(0)