Cython: Convert memory view to NumPy array

后端 未结 1 1927
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 13:23

How to convert a typed memoryview to an NumPy array in cython? The docs have

cimport numpy as np
import numpy as np

numpy_array = np.asarray(

        
相关标签:
1条回答
  • 2021-01-01 13:32

    You should just be able to use np.asarray directly on the memoryview itself, so something like:

    np.asarray(my_memview)
    

    should work. For example if your cython source file contains this:

    import numpy as np
    cimport numpy as np
    def test(double[:,:] x):
        print type(x)
        print type(np.asarray(x))
    

    Then after compiling it, you should be able to do the following from the python side:

    a = np.random.normal(size=(5,5))
    test(a)
    

    Which produces the following output:

    <type '_cython_magic_0182fca918bfa3618c3553e51b13e8ba._memoryviewslice'>
    <type 'numpy.ndarray'>
    

    Note: I'm using the cythonmagic extension for IPython.

    0 讨论(0)
提交回复
热议问题