Python:调整坐标

标签 python coordinates

我有这个 Python 脚本,它应该调整一组三角形元素的坐标。该脚本应将节点的坐标从元素更改为元素的重心。下图是我针对该问题绘制的草图。

enter image description here

但是我的脚本出了问题,我不知道是什么问题。坐标没有按照正确的方向改变,并且生成了额外的新坐标,而我只想调整现有的坐标。

有人知道如何用Python正确编程吗?

coords = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [0.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 1.0], [1.0, 1.0], [0.0, 2.0], [0.0, 2.0], [1.0, 1.0], [1.0, 2.0], [1.0, 1.0], [2.0, 1.0], [1.0, 2.0], [1.0, 2.0], [2.0, 1.0], [2.0, 2.0], [1.0, 1.0], [2.0, 0.0], [2.0, 1.0], [1.0, 0.0], [2.0, 0.0], [1.0, 1.0]]
elems = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19, 20], [21, 22, 23]]

#define vectors
def add_vectors(*points):
  new_x = 0.0
  new_y = 0.0
  for point in points:
    new_x += point[0]
    new_y += point[1]
  return [new_x, new_y]

def subtract_vectors(a, b):
  new_x = a[0] - b[0]
  new_y = a[1] - b[1]
  return [new_x, new_y]


def mul_by_scalar(vector, scalar):
  new_x = vector[0] * scalar
  new_y = vector[1] * scalar
  return [new_x, new_y]

#define triangles
triangles = []
for elem in elems:
    triangles += [coords[e] for e in elem]

#adjust coordinates
CM = mul_by_scalar(add_vectors(*triangles), 1.0/3)

point_to_CM_vectors = []
for point in triangles:
  point_to_CM_vectors.append(subtract_vectors(CM, point))

new_triangle = []
for elem in elems:
    for point, motion in zip(triangles, point_to_CM_vectors):
      new_triangle.append(add_vectors(point, mul_by_scalar(motion, 0.01)))

print 'triangles =', triangles
print 'new_triangle =', new_triangle

预先感谢您的帮助!

最佳答案

这里使用 numpy 提供的矢量化运算符对您的问题进行了改造。

import numpy as np

#define triangles
triangles = np.array([[coords[e] for e in elem] for elem in elems])

#find centroid of each triangle
CM = np.mean(triangles,axis=1)

#find vector from each point in triangle pointing towards centroid
point_to_CM_vectors = CM[:,np.newaxis] - triangles

#calculate similar triangles 1% smaller
new_triangle = triangles + 0.01*point_to_CM_vectors

关于Python:调整坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15991536/

相关文章:

python - 客户端使用 python 套接字接收两条单独的消息

python - 从长度为 n 的序列中选择 m 个均匀分布的元素

python - 如何对 pandas 中的列进行多数投票

ios - 如何在 iOS 中给定中心点和角度画线?

android - 如何获得 Android Touch 事件(运动事件)的开始和结束坐标?

python - 映射后的数字格式?

python - 更改不正确的python路径ubuntu

javascript - e.screenY 给出错误的值(鼠标坐标)

python - 获取二维数组特定值的位置

android - 将 GPS 转换为 ENU