2016-08-18 76 views
-1

爲什麼我的C函數中會出現截斷數組?爲什麼我的PyArrayObject *數據被截斷?

在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() 

當我試圖與不同尺寸的圖像I得到相同的結果(數據的9/10被移除)。

+2

爲什麼你打電話給'strlen'?你沒有處理一個字符串。 – user2357112

+0

我試圖改變這個數組for循環,它會崩潰,如果我超越25313,並且只有1/10(大約)的圖像發生了變化(我認爲字符串只是連續的字節)。 –

+0

@Anatoly C字符串是'\ 0'終止'char'數組。 'strlen'和其他'str *'函數被設計用於處理那種數據。沒有辦法獲得一個數組的大小(當然,除非它是一個固定大小的數組,在這種情況下,你可以在其類型中使用'sizeof')。你必須明確地跟蹤它的大小。如答案中所示,numpy數組是* multidimensional *數組,因此它們會跟蹤每個維度的大小,並且必須處理它。 – Bakuriu

回答

2

strlen會計入您的數據中的前0(它是爲空終止文本字符串設計的)。另外,如果遇到的第一個0在之後是,那麼您的數據已經完成,那麼它會返回一個太大的數字,這意味着您可能會嘗試寫入不屬於您的數據。

要計算出pyarrayobject的大小,您需要使用arr->nd計算出維數,然後用arr->dimensions(數組)計算出每個維度的大小。您還應該使用arr->descr來確定您的數組的數據類型,而不是將它作爲char來測試。