為了學習新的知識,我目前正在嘗試在C中重新實現(xiàn)numpy.mean()函數(shù)。它應該采用3D數(shù)組,并返回2D數(shù)組,其元素沿軸0的均值。所有值的均值,但真的不知道如何將新數(shù)組返回給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();}到目前為止,我所了解的(如果我錯了,請糾正我)是我需要創(chuàng)建一個new PyArrayObject,這將是我的輸出(也許帶有PyArray_FromDims?)。然后,我需要一個地址數(shù)組到該數(shù)組的內(nèi)存中,并用數(shù)據(jù)填充它。我將如何處理?
2 回答

蠱毒傳說
TA貢獻1895條經(jīng)驗 獲得超3個贊
Numpy API的功能PyArray_Mean可以完成您要嘗試執(zhí)行的操作,而不會出現(xiàn)“丑陋的循環(huán)”;)。
static PyObject *func1(PyObject *self, PyObject *args) {
PyArrayObject *X, *meanX;
int axis;
PyArg_ParseTuple(args, "O!i", &PyArray_Type, &X, &axis);
meanX = (PyArrayObject *) PyArray_Mean(X, axis, NPY_DOUBLE, NULL);
return PyArray_Return(meanX);
}
添加回答
舉報
0/150
提交
取消