0

I'm doing some Cython wrapping and it come up that I need to convert a pointer to an array of unsigned chars to a numpy array. None of the methods I've tried have worked. Also, I'd prefer to do it without actually copying the data if that's possible.

Here's the function in question I've been messing with.

def getImage(self):
    cdef int size = self.c_cam.getResolution()[0]*self.c_cam.getResolution()[1]*3

    return np.ctypeslib.as_array(self.c_cam.getImage(), shape=size*sizeof(unsigned char))

self.c_cam.getImage() returns a pointer to the data array (stored as a member of the c_cam class) However, this throws

AttributeError: 'str' object has no attribute '__array_interface__'

when run. Although frankly I don' know how it would work because there is nothing indicating the data type.

EDIT: So I've gotten the following to at least work

    cdef unsigned char* data = self.c_cam.getImage()
    dest = np.empty(size)
    for i in range(0,size):
        dest[i] = <int> data[i]
    return dest

but obviously this involves copying the data so I'd still want to find another way to do this.

Msquared
  • 842
  • 1
  • 6
  • 13

1 Answers1

1

I believe I've got an answer that avoids copying

import ctypes as c
from libc.stdint cimport uintptr_t[1]*3
data = <uintptr_t>self.c_cam.getImage()     
data_ptr = c.cast(data, c.POINTER(c.c_uint8))
array = np.ctypeslib.as_array(data_ptr, shape=(SIZE,))
Msquared
  • 842
  • 1
  • 6
  • 13