将指向无符号字符数组的指针转换为 Numpy 数组 [英] Convert Pointer to Array of Unsigned Chars to Numpy Array

查看:33
本文介绍了将指向无符号字符数组的指针转换为 Numpy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些 Cython 包装,结果发现我需要将指向无符号字符数组的指针转换为 numpy 数组.我尝试过的方法都没有奏效.此外,如果可能的话,我更愿意在不实际复制数据的情况下执行此操作.

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() 返回指向数据数组的指针(存储为 c_cam 类的成员)然而,这会抛出

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.

所以我已经得到以下至少工作

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.

推荐答案

我相信我有一个避免复制的答案

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,))

这篇关于将指向无符号字符数组的指针转换为 Numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆