为什么我的PyArrayObject*数据被截断?

2024-05-19 13:09:35 发布

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

为什么在我的C函数中得到截断数组?你知道吗

在C中:

#include <Python.h>
#include <arrayobject.h>

PyObject *edge(PyObject *self, PyObject *args) {
    int *ptr;
    unsigned char *charPtr;
    PyArrayObject *arr;
    PyObject *back;
    int ctr = 0;
    int size = 500 * 500;

    if (!PyArg_ParseTuple(args, "O", &arr))
        return NULL;

    charPtr = (char*)arr->data;
    printf("\n strlen of charPtr is ---> %d \n", strlen(arr->data)); // --->> 25313 
    printf("\n strlen of charPtr is ---> %d \n", strlen(charPtr));  //--->> also 25313 

    back = Py_BuildValue("s", "Nice");
    return back;
}

在Python中:

import ImageProc
import cv2
import numpy
import matplotlib.pyplot as plt

img = cv2.imread("C:/Users/srlatch/Documents/Visual Studio 2015/Projects/PythonImage/andrew.jpg", cv2.IMREAD_GRAYSCALE)
np =  cv2.resize(img, (500,500))

for i in np:
  for k in i:
      count += 1

print("Size before passing to edge " + str(count) ) // --->>  250000 

result = ImageProc.edge(np)
cv2.imshow("image", np)
cv2.waitKey()

当我尝试用不同大小的图像时,我得到了相同的结果(9/10的数据被删除)。你知道吗


Tags: importdatareturnincludenpbackargscv2
1条回答
网友
1楼 · 发布于 2024-05-19 13:09:35

strlen统计到数据中的第一个0(它是为以null结尾的文本字符串设计的)。另外,如果它遇到的第一个0是您的数据完成之后,那么它将返回一个太大的数字,这意味着您可能会尝试写入您不拥有的数据。你知道吗

要计算pyarrayobject的大小,需要使用arr->nd计算维度的数量,然后使用arr->dimensions(数组)计算每个维度的大小。您还应该使用arr->descr来确定数组的数据类型,而不仅仅是将其作为char进行测试。你知道吗

相关问题 更多 >