将numpy数组转换为ctype数组的最快方法是什么? [英] What is the fastest way of converting a numpy array to a ctype array?

查看:698
本文介绍了将numpy数组转换为ctype数组的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一小段代码,我必须将numpy数组转换为c_float ctype数组,以便将其传递给C语言的某些函数:

Here is a snippet of code I have to convert a numpy array to c_float ctype array so I can pass it to some functions in C language:

arr = my_numpy_array
arr = arr/255.
arr = arr.flatten()
new_arr = (c_float*len(arr))()
new_arr[:] = arr

但是由于最后一行实际上是一个for循环,而且我们都知道python对于中等大小的图像数组的for循环是多么臭名昭著,大约需要0.2秒!!所以这一行现在是我整个流程的瓶颈.我想知道是否有更快的方法.

but since the last line is actually a for loop and we all know how notorious python is when it comes to for loops for a medium size image array it takes about 0.2 seconds!! so this one line is right now the bottle neck of my whole pipeline. I want to know if there is any faster way of doing it.

请注意问题中的传递给C语言中的函数" .更具体地说,我想将一个numpy数组放入IMAGE数据结构中,并将其传递给rgbgr_image函数.您可以在此处

Please note "to pass to a function in C" in the question. To be more specific I want to put a numpy array in IMAGE data structure and pass it to rgbgr_image function. You can find both here

推荐答案

所以我设法使用numpy以这种怪异的方式做到了:

So I managed to do it in this weird way using numpy:

arr = my_numpu_array
arr = arr/255.
arr = arr.flatten()
arr_float32 = np.copy(arr).astype(np.float32)
new_arr = np.ctypeslib.as_ctypes(arr_float32)

就我而言,它的运行速度快了10倍.

In my case it works 10 times faster.

:我不知道为什么没有np.copyreshape(-1)它将不起作用.因此,如果任何人都可以解释,那就太好了.

: I don't know why it doesn't work without np.copy or with reshape(-1). So it would be awesome if anyone can explain.

这篇关于将numpy数组转换为ctype数组的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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