【发布时间】:2013-08-16 09:54:44
【问题描述】:
我在 numpyarray 和 C++ 代码中有二维数据,我想对这些数据执行一些操作。使用 swig 和 distutils 以及 numpy.i 我设法将所有内容编译成 python 扩展“goldstein”,它提供了一个函数unwrap2d。
我使用它测试它
import goldstein
data = np.ascontiguousarray(data_temp, dtype='double')
mask = np.ascontiguousarray(mask_temp, dtype='uint16')
outdata = np.ones_like(data)
goldstein.unwrap2d(data,mask,outdata)
我收到了TypeError: array cannot be safely cast to required type。谁能指出我如何以正确的方式传递这些数组?
供参考:为了创建模块,我使用了接口文件
%define DOCSTRING
"Wrapper for c++-code"
%enddef
%module(docstring=DOCSTRING) goldstein
%{
#define SWIG_FILE_WITH_INIT
#include "goldstein.h"
%}
/*include numpy typemaps*/
%include "numpy.i"
/*initialize module*/
%init %{
import_array();
%}
%rename(unwrap2d) phase_unwrapping_func;
/* typemaps for the arrays*/
%apply (int DIM1,int DIM2,float* IN_ARRAY2) {(int xsize,int ysize,float* in)};
%apply (int DIM1,int DIM2,unsigned short* IN_ARRAY2) {(int x1,int y1,unsigned short* mask)};
%apply (int DIM1,int DIM2,float* INPLACE_ARRAY2) {(int x2,int y2,float* out)};
/*wrapper function calling the original phase_unwrapping using only the needed parameters*/
%inline %{
void phase_unwrapping_func(int xsize,int ysize,float* in,int x1,int y1,unsigned short* mask,int x2,int y2,float* out) {
phase_unwrapping(xsize, ysize, in, mask, out);
}
%}
【问题讨论】:
-
我尝试打开语法高亮,但没有成功... :(
-
您的
data数组是双精度数据类型,但您的 C 函数需要浮点数。这可能就是让 NumPy 抱怨的原因。在调用你的函数之前执行data = np.ascontiguousarray(data_temp, dtype='float')应该注意这一点。