如何在图像中心周围旋转多个矩形坐标

时间:2018-05-28 00:17:54

标签: python image numpy scipy

当涉及到测试计算机视觉算法对象检测时,通过旋转测试图像,可以检测到一些错过的对象。通过这样做,那些检测到的由矩形中每个点的(x,y)坐标表示的对象位置应该向后旋转。物体检测器的输出是Numpy阵列,其包含例如100个元素,每个元素具有4对点,表示检测到的对象周围的矩形的(x,y)坐标,即具有(100,8)形状的Numpy阵列。在旋转版本的原始图像中检测到这些对象。因此,必须将它们旋转回来以便在原始图像上进行可视化。原始图像的分辨率为5616x3744像素,所以旋转版本为例如90度有3744x5616px。

  • 每一行都像[x1,y1,x2,y2,x3,y3,x4,y4]

问题是我们如何在图像中心周围的一行中旋转所有这些点,我们认为这是(2808,1872)。当我运行以下代码时,Python会抛出ValueError: operands could not be broadcast together with shapes (1000,8) (2,)的错误,这是有道理的。在这种情况下,速度很重要。所以我试图避免使用for循环。

def Rotate2D(pts,cnt,degree):
    ang = math.radians(degree)
    '''pts = {} Rotates points(nx2) about center cnt(2) by angle ang(1) in radian'''
    return scipy.dot(pts-cnt,scipy.array([[scipy.cos(ang),scipy.sin(ang)],[-scipy.sin(ang),scipy.cos(ang)]]))+cnt

2 个答案:

答案 0 :(得分:3)

问题是你试图减去“中心” - 来自(100, 8)“坐标数组的2元素向量”。在什么空间? 8D?如果是这样,中心也应该是8个坐标的列表,因为8D空间中的点是通过沿8个轴中的每个轴提供坐标来定义的。

如果坐标数组的形状为(100, 2),则代码可以正常工作。

如果,当你说“100个元素,每个元素有8个点代表(x,y)时,你的意思是数组中的每一行包含4个(不是8个)点(即,对的xy),例如x1y1x2y2x3y3x4y4,然后处理此问题的最佳方法是重塑您的pts数组:

import numpy as np
def Rotate2D(pts, cnt, degree):
    ang = math.radians(degree)
    m = scipy.array([[scipy.cos(ang), scipy.sin(ang)],
                     [-scipy.sin(ang), scipy.cos(ang)]])
    rpts = scipy.dot(np.reshape(pts, (pts.size // 2, 2)) - cnt, m) + cnt
    rpts = np.reshape(rpts, pts.shape)

答案 1 :(得分:-1)

在@AGNGazer的帮助下,这个问题得到了回答。 首先需要将所有点转移到中心附近:[0,0] 为了简单起见和90度旋转,让我们考虑一个2个对象而不是100个对象。

old_coord = np.zeros((2,8))
old_coord [0] = [500, 500, 510, 500, 510, 510, 500, 510] # only filling one is enough to show the functionality.

使用旋转图像中心[1872,2808]转移到中心。

old_coord [:, list(range(0, 8, 2))] -= 1872
old_coord [:, list(range(1, 8, 2))] -= 2808

应用@AGNGazer的功能。

new_coord = Rotate2D(old_coord, [0, 0], 90)

转移到原始图像中心[1872,2888]

new_coord [:, list(range(1, 8, 2))] += 1872
new_coord [:, list(range(0, 8, 2))] +=  2808
>>> new_coord
array([[5116.,  500., 5116.,  510., 5106.,  510., 5106.,  500.],
   [0.,  0., 0.,  0., 0.,  0., 0.,  0.]])
相关问题