How to convert raw byte data from a C# library to an image?

I have a MATLAB application that .NET library embedded into my MATLAB application. One of the functions in the C# library returns an image in a System byte array. I would like take this raw byte data and convert it to an image. The raw data come in byte[] as well as byte[,]. I tried to use the 'NET.createArray' function and the reshape function to convert the image to an image matrix but I'm having trouble.

 Accepted Answer

Assuming you have a .NET method that returns a 1D byte[] array containing the image data, you'd first have to convert the array to a MATLAB array using the uint8 function. (For more information see Convert Arrays of Primitive .NET Type to MATLAB Type).
matlabArray = uint8(byteArray)
For a greyscale image, you need to know the width and height. An example is below:
% Example for a grayscale image
imageMatrix = reshape(matlabArray, [width, height]).'; % Transpose to correct orientation
imshow(imageMatrix);
For an RGB image, reshape the array into a 3D matrix of size [height, width, 3], like shown below:
% Example for an RGB image
imageMatrix = reshape(matlabArray, [3, width, height]);
imageMatrix = permute(imageMatrix, [3, 2, 1]); % Rearrange dimensions to [height, width, 3]
imshow(imageMatrix);
The process is very similar when working with a 2D byte array. Because MATLAB primarily works with 1D arrays, you'll need to first convert the 2D byte array into a 1D array that MATLAB can work with. Some example steps are below:
  • Flatten the byte array: You might need to write a helper method in C# that flattens the 2D array into a 1D array before sending it to MATLAB. You can also handle the conversion in MATLAB by accessing each element individually but this is less efficient and it's often easier to handle the conversion on the .NET side. 
  • Once converting to a 1D array and then to a MATLAB array, follow the similar reshape steps as mentioned for the 1D array. 
For more information about using .NET libraries in MATLAB, see Call .NET from MATLAB.
 

More Answers (0)

Categories

Tags

No tags entered yet.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!