4

这是共同计算平移和旋转的正确方法,还是有更好的方法?目前我的代码翻译然后旋转,这会造成问题吗?

代码

from math import cos, sin, radians

def trig(angle):
  r = radians(angle)
  return cos(r), sin(r)

def matrix(rotation=(0,0,0), translation=(0,0,0)):
  xC, xS = trig(rotation[0])
  yC, yS = trig(rotation[1])
  zC, zS = trig(rotation[2])
  dX = translation[0]
  dY = translation[1]
  dZ = translation[2]
  return [[yC*xC, -zC*xS+zS*yS*xC, zS*xS+zC*yS*xC, dX],
    [yC*xS, zC*xC+zS*yS*xS, -zS*xC+zC*yS*xS, dY],
    [-yS, zS*yC, zC*yC, dZ],
    [0, 0, 0, 1]]

def transform(point=(0,0,0), vector=(0,0,0)):
  p = [0,0,0]
  for r in range(3):
    p[r] += vector[r][3]
    for c in range(3):
      p[r] += point[c] * vector[r][c]
  return p

if __name__ == '__main__':
  point = (7, 12, 8)
  rotation = (0, -45, 0)
  translation = (0, 0, 5)
  matrix = matrix(rotation, translation)
  print (transform(point, matrix))

输出

root@ubuntu:~$ python rotate.py 
[-0.707106781186547, 12.0, 15.606601717798213]
4

1 回答 1

2

好吧,您的矩阵函数很好,我可以正常工作,但是对于输出,我使用了这个:

#def transform(point, vector):
#  p = [0,0,0]
#  for r in range(0,3):
#    p[r] += vector[r][3]
#    print p
#    for c in range(3):
#        p[r] += point[c] * vector[r][c]
#  return p

def transform(point, TransformArray):
  p = np.array([0,0,0,1])
  for i in range (0,len(point)-1):
      p[i] = point[i]
  p=np.dot(TransformArray,np.transpose(p))
  for i in range (0,len(point)-1):
      point[i]=p[i]
  return point

如果不是执行手动更改,而是让矩阵对其进行排序,则其背后的理论。在这里您可以找到文献以更好地理解我所做的:http: //www.inf.ed.ac.uk/teaching/courses/cg/lectures/cg3_2013.pdf

是的,您执行矩阵函数的方式定义了您执行转换顺序的方式。有 3 种主要的变换:缩放、平移和旋转。更多关于我发送的链接。

尽管矩阵函数有效,但您现在似乎错误地交换了 x 和 z 旋转,我现在可以跟随您的任何矩阵索引,因此我将其重写为:

def matrix(rotation, translation):
  xC, xS = trig(rotation[0])
  yC, yS = trig(rotation[1])
  zC, zS = trig(rotation[2])
  dX = translation[0]
  dY = translation[1]
  dZ = translation[2]
  Translate_matrix = np.array([[1, 0, 0, dX],
                               [0, 1, 0, dY],
                               [0, 0, 1, dZ],
                               [0, 0, 0, 1]])
  Rotate_X_matrix = np.array([[1, 0, 0, 0],
                              [0, xC, -xS, 0],
                              [0, xS, xC, 0],
                              [0, 0, 0, 1]])
  Rotate_Y_matrix = np.array([[yC, 0, yS, 0],
                              [0, 1, 0, 0],
                              [-yS, 0, yC, 0],
                              [0, 0, 0, 1]])
  Rotate_Z_matrix = np.array([[zC, -zS, 0, 0],
                              [zS, zC, 0, 0],
                              [0, 0, 1, 0],
                              [0, 0, 0, 1]])
  return np.dot(Rotate_Z_matrix,np.dot(Rotate_Y_matrix,np.dot(Rotate_X_matrix,Translate_matrix)))

如您所见,我返回的转换序列将改变输出:由于最后一个是平移,因此它将首先平移该点,然后在 X 中旋转,然后在 Y 中旋转,最后在 Z 中旋转。希望这有助于欢呼芽。

于 2017-06-27T13:07:36.227 回答