Skip to content Skip to sidebar Skip to footer

What Is The Fastest Way Of Converting A Numpy Array To A Ctype Array?

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.fla

Solution 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.

Solution 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.

Post a Comment for "What Is The Fastest Way Of Converting A Numpy Array To A Ctype Array?"