What is the fastest way of converting a numpy array to a ctype array?

笑着哭i 提交于 2019-12-11 15:52:22

问题


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

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.

Update

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


回答1:


The OP's answer makes 4 copies of the my_numpu_array, at least 3 of which should be unnecessary. Here's a version that avoids them:

# random array for demonstration
my_numpy_array = np.random.randint(0, 255, (10, 10))

# copy my_numpy_array to a float32 array
arr = my_numpy_array.astype(np.float32)

# divide in place
arr /= 255

# reshape should return a view, not a copy, unlike flatten
ctypes_arr = np.ctypeslib.as_ctypes(arr.reshape(-1))

In some circumstances, reshape will return a copy, but since arr is guaranteed to own it's own data, it should return a view here.




回答2:


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)

In my case it works 10 times faster.

[Edit]: 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.



来源:https://stackoverflow.com/questions/53755064/what-is-the-fastest-way-of-converting-a-numpy-array-to-a-ctype-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!