有效地将System.Single [,]转换为numpy数组 [英] Efficiently convert System.Single[,] to numpy array

查看:155
本文介绍了有效地将System.Single [,]转换为numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用适用于dotNET/pythonnet的Python 3.6和Python我已经设法获得一个图像数组.此类型为System.Single [,]

Using Python 3.6 and Python for dotNET/pythonnet I have manged to get hold of an image array. This is of type System.Single[,]

我想将其转换为numpy数组,以便实际上可以在Python中对其进行处理.我已经设置了一个函数来逐步遍历该数组并按元素进行转换-但是我可以使用更明智(更快)的东西吗?

I'd like to convert that to a numpy array so that I can actually do something with it in Python. I've set up a function to step through that array and convert it elementwise - but is there something more sensible (and faster) that I could use?

def MeasurementArrayToNumpy(TwoDArray):
    hBound = TwoDArray.GetUpperBound(0)
    vBound = TwoDArray.GetUpperBound(1)

    resultArray = np.zeros([hBound, vBound])

    for c in range(TwoDArray.GetUpperBound(0)):            
            for r in range(TwoDArray.GetUpperBound(1)):
                resultArray[c,r] = TwoDArray[c,r]
    return resultArray

推荐答案

@denfromufa-这是一个非常有用的链接.

@denfromufa - that is a very useful link.

建议使用Marshal.Copy或np.frombuffer进行直接内存复制.我无法使Marshal.Copy版本正常工作-一些shenanigans需要与Marshal一起使用2D数组,并且以某种方式更改了数组的内容-但是np.frombuffer版本似乎对我有用,并减少了对于3296 * 2471阵列,完成时间约为〜16000(约25s->〜1.50ms).这对我来说已经足够了

The suggestion there is to do a direct memory copy, either using Marshal.Copy or np.frombuffer. I couldn't manage to get the Marshal.Copy version working - some shenanigans are required to use a 2D array with Marshal and that changed the contents of of the array somehow - but the np.frombuffer version seems to work for me and reduced the time to complete by a factor of ~16000 for a 3296*2471 array (~25s -> ~1.50ms). This is good enough for my purposes

该方法需要多次导入,因此我已将其包含在下面的代码段中

The method requires a couple more imports, so I've included those in the code snippet below

import ctypes
from System.Runtime.InteropServices import GCHandle, GCHandleType

def SingleToNumpyFromBuffer(TwoDArray):
    src_hndl = GCHandle.Alloc(TwoDArray, GCHandleType.Pinned)

    try:
        src_ptr = src_hndl.AddrOfPinnedObject().ToInt32()
        bufType = ctypes.c_float*len(TwoDArray)
        cbuf = bufType.from_address(src_ptr)
        resultArray = np.frombuffer(cbuf, dtype=cbuf._type_)
    finally:
        if src_hndl.IsAllocated: src_hndl.Free()
    return resultArray

这篇关于有效地将System.Single [,]转换为numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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