使用ctypes.memmove()从ctypes POINTER创建numpy数组会产生错误的结果

时间:2016-09-02 10:37:54

标签: python c++ numpy ctypes memmove

我使用ctypes调用C ++函数并计算单应性。然后它被转换成一个numpy数组。用C ++打印的单应性是正确的。然而,在python中,使用ctypes.memmove()转换为numpy数组后,它完全错误。

例如,在C ++中,单应性是:

  

[[0.999931,3.05449e-06,0.0219359],

     

[ - 3.46952e-05,1.00000024,0.0162477],

     

[ - 1.20569e-08,-6.80167e-09,1]]

在Python中,trs_matrix(单应性)是:

  

[[3.36311631e-44,0.00000000e + 00,2.25339716e + 12]

     

[4.59163468e-41,2.25339612e + 12,4.59163468e-41]

     

[2.25339821e + 12,4.59163468e-41,2.24207754e-44]]

Python代码:

def find_homo(self, numLoops=1000, minScore=0.85, maxAmbiguity=0.95, thresh=5.0):

    homography = ctypes.POINTER(ctypes.c_float)()

    num_match = _LIB.FindHomography_C(
        ctypes.byref(self),
        ctypes.byref(homography),
        ctypes.c_int(numLoops),
        ctypes.c_float(minScore),
        ctypes.c_float(maxAmbiguity),
        ctypes.c_float(thresh)
    )

    trs_matrix = ctypes2numpy(homography, 9, np.float32).reshape((3, 3))

    return trs_matrix, num_match


def ctypes2numpy(cptr, length, dtype):
    #Convert a ctypes pointer array to a numpy array

    if not isinstance(cptr, ctypes.POINTER(ctypes.c_float)):
        raise RuntimeError('Expected float pointer')

    res = np.zeros(length, dtype=dtype)

    if not ctypes.memmove(res.ctypes.data, cptr, length * res.strides[0]):
        raise RuntimeError('memmove failed')

    return res

C ++代码:

int FindHomography_C(SiftData &data, float** out_homo, int numLoops, float minScore, float maxAmbiguity, float thresh){
    //API_BEGIN();
    int numMatches = 0;

    float homography[9];

    FindHomography(data, homography,  &numMatches, numLoops, minScore, maxAmbiguity, thresh);

    *out_homo = &homography[0];

    return numMatches;
}

0 个答案:

没有答案