如何将参数传递到python函数bug中

2024-10-02 18:18:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段代码:

   points = np.array([[207.0,489.0], [500.0,58.0], [84.0,17.0],[197.0,262.0]])
    #read data from the csv file 
    x = df["XC"]
    y = df["YC"]
    # make the x,y a point type 
    pointP = np.array([x,y])
    #print(pointP)
    rW,rV,rU = calcRatios(points,pointP,ratioU,ratioV,ratioW)

这就是calcRatios函数

def calcRatios(points,centreP,ratioU,ratioV,ratioW):
    v0 = points[1] - points[0]
    v1 = points[2] - points[0]
    v2 = centreP - points[0]
    #dot product of the vects
    d00 = np.dot(v0, v0)
    d01 = np.dot(v0, v1)
    d11 = np.dot(v1, v1)
    d20 = np.dot(v2, v0)
    d21 = np.dot(v2, v1)
    #calc denom
    denom = d00 * d11 - d01 * d01
    #barycentric ratios of v,w,u
    ratioV = (d11 * d20 - d01 * d21) / denom
    ratioW = (d00 * d21 - d01 * d20) / denom
    ratioU = 1.0 - ratioV - ratioW
    return ratioV,ratioW,ratioU

数据帧中的数据存储方式如下:

       Index      XC      YC    R    G    B
           1       0       0  227  227  227
           2       1       0  237  237  237
           3       2       0   0     0    0
           4       3       0  232  232  232
           5       4       0  233  233  233
...        ...     ...     ...  ...  ...  ...

然而,现在我传递到函数中的centreP点似乎有问题,我不知道为什么

我得到的错误是:ValueError: operands could not be broadcast together with shapes (2,28686) (2,)对于此行v2 = centreP - points[0]

有人能告诉我为什么会发生这种情况以及应该如何解决吗

谢谢大家!


Tags: thenpdotpointsv2v1v0denom
2条回答

您的centreP是由两个长数组组成的数组:[[0, 1, 2...], [0,0,0...]],而points[0]是长度为2的单个数组[207.0,489.0]。numpy的broadcasting rules无法处理这两个形状的减法运算。但是,如果将centreP转置为[[0,0], [1,0], [2,0]...],它将通过从每行中减去points[0]来处理此问题:

 v2 = centreP.T - points[0]

更好的是,传递df[[XC, YC]]而不是pointP-它将被强制为正确形状的numpy数组

rW,rV,rU = calcRatios(points, df[["XC","YC"]]) # no need to transpose

np.array([x,y])将返回数组数组,而不是您所期望的。如果您希望在xy中有一个点数组,那么这将完成此任务

pointP = np.array([[a, b] for a, b in zip(x, y)])  

相关问题 更多 >