【问题标题】:Convert C# byte array to numpy array in Python .Net在 Python .Net 中将 C# 字节数组转换为 numpy 数组
【发布时间】:2016-06-16 12:52:09
【问题描述】:

我尝试在使用 Python.NET 的 Python 应用程序中使用 .NET 程序集。 C# 代码捕获我想与 python 一起使用的图像。假设我有以下 C# 方法:

public static byte[] Return_Image_As_Byte_Array()
    {
        Image image = Image.FromFile("C:\path\to\an\image");
        ImageConverter imageConverter = new ImageConverter();
        byte[] ByteArray = (byte[])imageConverter.ConvertTo(image, typeof(byte[]));
        return ByteArray;
    }

当我在 python 中使用 Python.Net 时,我会执行以下操作:

import clr
clr.AddReference('MyAssembly')
from MyAssembly import MyClass
print(MyClass.Return_Image_As_Byte())

这给了我输出:

<System.Byte[] at 0xb7ba20c080>

有没有办法将此图像从 C# 转换为原生 python 类型,如 numpy 数组?

【问题讨论】:

标签: python .net arrays numpy python.net


【解决方案1】:

如果您正在寻找性能: 我发现 np.fromiter() (numpy) 比上面@dlammy url 链接中提供的答案快 6 倍作为对问题的回应。使用的函数是asNumpyArray() 网址:https://github.com/pythonnet/pythonnet/issues/514

由于时间上存在如此大的差异,我认为只需要一次定时运行就足够了,而不是平均结果。 我的结果: np.fromiter() : 67.914736s asNumpyArray(): 334.5198s

在这里找到解决方案:https://stackoverflow.com/a/61077271/4084346

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 2011-07-02
    • 2016-07-01
    • 1970-01-01
    • 2018-09-19
    • 2011-03-12
    • 2022-11-14
    相关资源
    最近更新 更多