为了学习新的知识,我目前正在尝试在C中重新实现numpy.mean()函数。它应该采用3D数组,并返回2D数组,其元素沿轴0的均值。所有值的均值,但真的不知道如何将新数组返回给Python。
到目前为止,我的代码:
#include <Python.h>
#include <numpy/arrayobject.h>
// Actual magic here:
static PyObject*
myexts_std(PyObject *self, PyObject *args)
{
PyArrayObject *input=NULL;
int i, j, k, x, y, z, dims[2];
double out = 0.0;
if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &input))
return NULL;
x = input->dimensions[0];
y = input->dimensions[1];
z = input->dimensions[2];
for(k=0;k<z;k++){
for(j=0;j<y;j++){
for(i=0;i < x; i++){
out += *(double*)(input->data + i*input->strides[0]
+j*input->strides[1] + k*input->strides[2]);
}
}
}
out /= x*y*z;
return Py_BuildValue("f", out);
}
// Methods table - this defines the interface to python by mapping names to
// c-functions
static PyMethodDef myextsMethods[] = {
{"std", myexts_std, METH_VARARGS,
"Calculate the standard deviation pixelwise."},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC initmyexts(void)
{
(void) Py_InitModule("myexts", myextsMethods);
import_array();
}
到目前为止,我所了解的(如果我错了,请纠正我)是我需要创建一个new PyArrayObject,这将是我的输出(也许带有PyArray_FromDims?)。然后,我需要一个地址数组到该数组的内存中,并用数据填充它。我将如何处理?
杨__羊羊
蛊毒传说
随时随地看视频慕课网APP
相关分类