【问题标题】:How to find the translation values after a rotate about a point for a 2D image?2D图像绕点旋转后如何找到平移值?
【发布时间】:2016-02-28 04:22:00
【问题描述】:

我在旋转图像后无法获取正确的平移值。到目前为止,我的代码使用基本三角法计算给定旋转的边界框,然后将平移应用于旋转矩阵。然而,我遇到的问题是我的翻译似乎总是超出 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 - 90° - 注意顶部的 1px 边框

coffee.png - 180° - 注意顶部和左侧的 1px 边框

我对数学不是很感兴趣,但我猜测这是由一些舍入问题引起的,因为我们正在处理浮点数。 我想知道其他人使用什么方法,请以最简单和最高效的方式旋转和平移图像的中心点?

谢谢。

编辑

根据@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

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

【问题讨论】:

    标签: python opencv rotation opencv3.0 affinetransform


    【解决方案1】:

    我猜你的图像中心是错误的。例如,使用 0、1、2 和 3 列的 4x4 图像。然后您的中心计算为 4 / 2 = 2。但它应该在第 1 列和第 2 列之间为 1.5。

    所以你最好使用 (width - 1) / 2.0 和 (height - 1) / 2.0。

    【讨论】:

    • 当然!!我们从 0 开始计数,而不是 1.. 我正在使用矩阵,而不是像素!感谢您指出这一点! :) 现在我对中心点的宽度/高度和 bound_w/bound_h 平移计算都做了 -1。它适合!谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-06-30
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 2016-12-12
    相关资源
    最近更新 更多