首页 > 解决方案 > 如何在 3d 空间中定义一个自定义的矢量点类并计算它们的中心(平均)点?

问题描述

我正在制作一个制作形状等的程序。我想通过查找其上存在的每个矢量点的平均值来找到脸部的中心(由 3d 矢量点列表提供)。这是我尝试过的:

import math

class vector:

    def __init__(self, x, y, z):

        self.x = x
        self.y = y
        self.z = z

class plane:

    def __init__(self, pointsList):

        self.vertex = []

        # check that each point is unique
        for p in range(0, len(pointsList)-1):


            for i in range(p+1, len(pointsList)):

                if (pointsList[p] != pointsList[i]):
                        if (i == len(pointsList)-1):
                            self.vertex.append(pointsList[p])

                else:
                    return None
        self.vertex.append(pointsList[-1])


    #returns the mean of x, y, and z            
    def center(self):

        xs = 0
        ys = 0
        zs = 0
        count = len(self.vertex)    

        for i in range(0, count):
            xs += self.vertex[i].x

            ys += self.vertex[i].y

            zs += self.vertex[i].z

        xMean = xs/count
        yMean = ys/count
        zMean = zs/count


        return vector(xMean, yMean, zMean)

然后我去测试函数plane.center():

#initialize some vectors
A = vector(1,7,5)
B = vector(3,9,4)
C = vector(0,1,0)
D = vector(0,0,0)

testList = [A, B, C, D]

#initialize a plane with those vectors
plane1 = plane(testList)

acenter = plane1.center()
print('%d %d %d' % (acenter.x, acenter.y, acenter.z))

然后返回的结果是1 4 2. 我想要 x 分量、y 分量和 z 分量4的平均值,但显然不是7, 9, 1, and 0. 预期的结果应该是1.0, 4.25, 2.25。我怎样才能做到这一点?

标签: pythonclassvector

解决方案


谢谢大家。是的,我现在看到了错误。这真的很简单,我觉得很傻。我认为这与我的解释器默认为 python 2 有关,但这显然是错误的。


推荐阅读