可以使用^{}函数围绕定义的中心点旋转图像。可以使用^{}(其中theta在度中)生成合适的旋转矩阵。
import cv2
import numpy as np
def subimage(image, center, theta, width, height):
'''
Rotates OpenCV image around center with angle theta (in deg)
then crops the image according to width and height.
'''
# Uncomment for theta in radians
#theta *= 180/np.pi
shape = ( image.shape[1], image.shape[0] ) # cv2.warpAffine expects shape in (length, height)
matrix = cv2.getRotationMatrix2D( center=center, angle=theta, scale=1 )
image = cv2.warpAffine( src=image, M=matrix, dsize=shape )
x = int( center[0] - width/2 )
y = int( center[1] - height/2 )
image = image[ y:y+height, x:x+width ]
return image
记住dsize是输出图像的形状。如果面片/角度足够大,如果使用原始形状(为了简单起见)执行上述操作,则边缘将被截断(比较上面的图像)。在这种情况下,可以将缩放因子引入到shape(放大输出图像)和切片的参考点(这里是center)。
上述功能可以使用如下:image = cv2.imread('owl.jpg')
image = subimage(image, center=(110, 125), theta=30, width=100, height=200)
cv2.imwrite('patch.jpg', image)