0
我正在開發一個python 2.7模塊,它使用從動態庫運行編譯函數。它包含一個類,該類包裝來自該庫的C結構,表示圖像,並用於接收來自C代碼的數據。如何使Python對象的行爲像一個numpy數組?
動態庫執行數據的深層副本,專門用於python包裝。
模塊中的進一步處理是使用numpy
數組完成的,因此,我應該將從C代碼中檢索到的數據轉換爲numpy.ndarray
。
速度和內存消耗現在不是問題。
現在,我已經在該類中實現了一個方法,該方法使用numpy.frombuffer
函數創建並返回numpy.ndarray
。
我想知道,如果它可以實施得更好。
這裏是蟒類
import ctypes as ct
import numpy as np
class C_Mat(ct.Structure):
_fields_ = [("rows", ct.c_int),
("cols", ct.c_int),
("data", ct.c_char_p),
("step", ct.ARRAY(ct.c_int64, 2)),
("data_type", ct.c_int)]
_dtypes = { 0: np.uint8,
1: np.int8,
2: np.uint16,
3: np.int16,
4: np.int32,
5: np.float32,
6: np.float64 }
def image(self):
r = np.frombuffer(self.data,
dtype=self._dtypes[self.data_type],
count=self.cols*self.step[1]*self.step[0])
r.shape = (self.cols, self.rows)
r.strides = (self.step[0], self.step[1])
return r