Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert C# byte array to numpy array in Python .Net

I try to use a .NET Assembly in a python application using Python.NET. The C# code captures an image, that i want to use with python. Let's say I have the following C# method:

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;
    }

When I use Python.Net in python i do the following:

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

This gives me the output:

<System.Byte[] at 0xb7ba20c080>

Is there a way to turn this image from C# into a native python type like numpy array?

like image 758
aPere Avatar asked Nov 20 '22 12:11

aPere


1 Answers

It's possible to convert C# Byte[] to Python bytes first and from that to numpy (Python 3.8):

from System import Byte, Array
import numpy as np

c_sharp_bytes = Array[Byte](b'Some bytes')  # <System.Byte[] object at 0x000001A33CC2A3D0>
python_bytes = bytes(c_sharp_bytes)
numpy_bytes = np.frombuffer(python_bytes, 'u1')  # b'Some bytes'
# numpy_bytes is now array([ 83, 111, 109, 101,  32,  98, 121, 116, 101, 115], dtype=uint8)

like image 138
phispi Avatar answered Nov 23 '22 02:11

phispi