6

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?

5
  • this looks like resolved here: github.com/pythonnet/pythonnet/issues/174 Commented Sep 13, 2016 at 5:44
  • 4
    you can just wrap with list(System.Byte[]) Commented Sep 13, 2016 at 5:44
  • @denfromufa this would have a very bad performance Commented Oct 19, 2020 at 15:24
  • 3
    @dlammy if you need performance, take a look here: github.com/pythonnet/pythonnet/issues/514 Commented Oct 19, 2020 at 21:24
  • @denfromufa Yes in fact I've used robbmcleod solution and it's very fast. thanks Commented Oct 21, 2020 at 13:00

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

If you are looking for Performance: I found that np.fromiter() (numpy) was 6 times faster than the provided answer in @dlammy url link above as response to the question. The used function was asNumpyArray() url: https://github.com/pythonnet/pythonnet/issues/514

Since there was such a distinction in times I thought only one timed run would suffice, instead of averaging the results. My Result: np.fromiter() : 67.914736s asNumpyArray(): 334.5198s

Solution Found here: https://stackoverflow.com/a/61077271/4084346

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.