简体   繁体   English

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

[英]Why my PyArrayObject* data truncated?

Why do i get truncated array inside my C function? 为什么我的C函数中会截断数组?

In 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;
}

In Python: 在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()

When I tried this with differently sized image I get the same result (9/10 of data is removed). 当我尝试使用不同大小的图像进行此操作时,我得到的结果是相同的(删除了9/10的数据)。

strlen counts as far as the first 0 in your data (it's designed for null terminated text strings). strlen计数到数据中的第一个0(它是为空终止的文本字符串设计的)。 Also, if the first 0 it encounters is after your data has finished then it'll return a number that's too big meaning you might try to write to data you don't own. 另外,如果它遇到的第一个0是数据完成之后,那么它将返回一个太大的数字,这意味着您可能会尝试写入不拥有的数据。

To work out the size of the pyarrayobject you need to use arr->nd to work out the number of dimensions then arr->dimensions (an array) to work out how big each dimension is. 要计算pyarray对象的大小,您需要使用arr->nd来计算维数,然后使用arr->dimensions (数组)来计算每个维的大小。 You should also use arr->descr to work out what data type your array is rather than just testing it as char. 您还应该使用arr->descr来确定数组是哪种数据类型,而不仅仅是将其测试为char。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM