<p>可以使用<a href="https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_geometric_transformations/py_geometric_transformations.html#rotation" rel="noreferrer">^{<cd1>}</a>函数围绕定义的中心点旋转图像。可以使用<a href="https://docs.opencv.org/3.4.0/da/d54/group__imgproc__transform.html#gafbbc470ce83812914a70abfb604f4326" rel="noreferrer">^{<cd2>}</a>(其中<code>theta</code>在<em>度</em>中)生成合适的旋转矩阵。</p>
<p><img src="https://i.stack.imgur.com/Zu4Y2.jpg" alt="Start Image"/><img src="https://i.stack.imgur.com/xw4jh.jpg" alt="After finding the desired rectangle"/></p>
<p>然后可以使用<a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="noreferrer">Numpy slicing</a>剪切图像。</p>
<p><a href="https://i.stack.imgur.com/6oB6V.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/6oB6V.jpg" alt="Rotated Image"/></a><img src="https://i.stack.imgur.com/fs9T5.jpg" alt="Result"/></p>
<pre><code>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
</code></pre>
<p>记住<code>dsize</code>是<em>输出</em>图像的形状。如果面片/角度足够大,如果使用原始形状(为了简单起见)执行上述操作,则边缘将被截断(比较上面的图像)。在这种情况下,可以将缩放因子引入到<code>shape</code>(放大输出图像)和切片的参考点(这里是<code>center</code>)。</p>
<p>上述功能可以使用如下:</p>
<pre><code>image = cv2.imread('owl.jpg')
image = subimage(image, center=(110, 125), theta=30, width=100, height=200)
cv2.imwrite('patch.jpg', image)
</code></pre>