在旋转图像后,我遇到了获取正确翻译值的问题。到目前为止,我编写的代码使用基本三角函数计算给定旋转的边界框,然后将平移应用于旋转矩阵。然而,我遇到的问题是我的平移似乎总是有1个像素的偏差,我的意思是我在旋转后的图像顶部或侧面得到了一个1像素的黑色边框。
这是我的代码:
def rotate_image(mat, angle):
height, width = mat.shape[:2]
image_center = (width / 2.0, height / 2.0)
rotation_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
# Get Bounding Box
radians = math.radians(angle)
sin = abs(math.sin(radians))
cos = abs(math.cos(radians))
bound_w = (width * cos) + (height * sin)
bound_h = (width * sin) + (height * cos)
# Set Translation
rotation_mat[0, 2] += (bound_w / 2.0) - image_center[0]
rotation_mat[1, 2] += (bound_h / 2.0) - image_center[1]
rotated_mat = cv2.warpAffine(mat, rotation_mat, (int(bound_w), int(bound_h)))
return rotated_mat
这里是参考原始图像和使用该代码的一些图像示例:
coffee.png - 180° - 注意顶部和左侧的1像素边框
我对数学不太在行,但我猜测这可能是由于浮点数的舍入问题引起的。 我想知道其他人使用的方法是什么,请问如何以最简单和高效的方式围绕中心点旋转和平移图像?
谢谢。
编辑
根据@Falko的回答,我没有使用从零开始的计算。我的更正代码如下:
def rotate_image(mat, angle):
height, width = mat.shape[:2]
image_center = ((width - 1) / 2.0, (height - 1) / 2.0)
rotation_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
# Get Bounding Box
radians = math.radians(angle)
sin = abs(math.sin(radians))
cos = abs(math.cos(radians))
bound_w = (width * cos) + (height * sin)
bound_h = (width * sin) + (height * cos)
# Set Translation
rotation_mat[0, 2] += ((bound_w - 1) / 2.0 - image_center[0])
rotation_mat[1, 2] += ((bound_h - 1) / 2.0 - image_center[1])
rotated_mat = cv2.warpAffine(mat, rotation_mat, (int(bound_w), int(bound_h)))
return rotated_mat
我仍然很想看到人们用来执行旋转和平移的替代方法!:)