如何在2D图像绕某一点旋转后找到平移值?

4

在旋转图像后,我遇到了获取正确翻译值的问题。到目前为止,我编写的代码使用基本三角函数计算给定旋转的边界框,然后将平移应用于旋转矩阵。然而,我遇到的问题是我的平移似乎总是有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 - 原始图像 coffee.png - 原始图像

coffee.png - 90° - 注意顶部的1像素边框 coffee.png - 90°

coffee.png - 180° - 注意顶部和左侧的1像素边框 coffee.png - 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

我仍然很想看到人们用来执行旋转和平移的替代方法!:)

1个回答

3
我猜你的图像中心位置不正确。例如,取一个4x4的图像,有列0、1、2和3。那么你的中心点计算为4/2=2。但实际上应该在第1列和第2列之间的1.5处。
因此,最好使用(宽度-1)/ 2.0和(高度-1)/ 2.0。

当然!我们从0开始算,而不是1..我正在处理矩阵,而不是像素!谢谢你指出这一点! :) 现在我在宽度/高度上都做了-1,并且在我的bound_w/bound_h转换计算中再次进行了-1。很合适!谢谢! - Robula

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接