Anatoly Anatoly - 2 months ago 4x
Python Question

Why my PyArrayObject* data truncated

Why do i get truncated array inside my C function?

In 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:

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)

When I tried this with differently sized image I get the same result (9/10 of data is removed).


strlen counts as far as the first 0 in your data (it's designed for null terminated text strings). 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.

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. You should also use arr->descr to work out what data type your array is rather than just testing it as char.