【发布时间】: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 - 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