from cv2 import cv
import numpy as np
def getSubImage(rect, src):
# Get center, size, and angle from rect
center, size, theta = rect
# Convert to int
center, size = tuple(map(int, center)), tuple(map(int, size))
# Get rotation matrix for rectangle
M = cv2.getRotationMatrix2D( center, theta, 1)
# Perform rotation on src image
dst = cv2.warpAffine(src, M, src.shape[:2])
out = cv2.getRectSubPix(dst, size, center)
return out
img = cv2.imread('img.jpg')
# Find some contours
thresh2, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Get rotated bounding box
rect = cv2.minAreaRect(contours[0])
# Extract subregion
out = getSubImage(rect, img)
# Save image
cv2.imwrite('out.jpg', out)
我在这里有错误的补偿问题,在类似的问题张贴解决方案。 所以我做了数学计算,得出了以下有效的解决方案:
作为参考,这里有一张图片解释了其背后的数学原理:
请注意
这是因为最后一个坐标的值是
width-1
,而不是width
;或者height
。如果有关于数学的问题,把它们当作评论来问,我会尽力回答。
可以使用^{} 函数围绕定义的中心点旋转图像。可以使用^{} (其中
theta
在度中)生成合适的旋转矩阵。然后可以使用Numpy slicing剪切图像。
记住
dsize
是输出图像的形状。如果面片/角度足够大,如果使用原始形状(为了简单起见)执行上述操作,则边缘将被截断(比较上面的图像)。在这种情况下,可以将缩放因子引入到shape
(放大输出图像)和切片的参考点(这里是center
)。上述功能可以使用如下:
openCV版本3.4.0的类似配方。
相关问题 更多 >
编程相关推荐