Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reshape an Array in c#

Tags:

arrays

c#

matrix

I have a 3D array of bytes in c# which I have read from a bitmap:

byte[w, h, 3]

What is the easiest and more performance-friendly way of reshaping this array into 2D (linear) form?

byte[w*h, 3]

In other words I want to keep number of channels (features) but in a linear shape (rather than a square shape)

Let me try to illustrate input and desired output:

input:

|(r1,g1,b1)    (r2,g2,b2)    (r3,g3,b3)|
|(r4,g4,b4)    (r5,g5,b5)    (r6,g6,b6)|
|(r7,g7,b7)    (r8,g8,b8)    (r9,g9,b9)|

note that arr[0, 0, 0] = r1, arr[0, 0, 1] = g1, arr[0, 0, 2] = b1, etc..

and output:

|(r1,g1,b1)    (r2,g2,b2)    (r3,g3,b3)    (r4,g4,b4)    (r5,g5,b5)    (r6,g6,b6) ...|
like image 918
Mo Valipour Avatar asked Jun 29 '11 14:06

Mo Valipour


People also ask

Why do we do reshape (- 1 1?

If you have an array of shape (2,4) then reshaping it with (-1, 1), then the array will get reshaped in such a way that the resulting array has only 1 column and this is only possible by having 8 rows, hence, (8,1).

What is the use of reshape () method?

reshape() function allows us to reshape an array in Python. Reshaping basically means, changing the shape of an array. And the shape of an array is determined by the number of elements in each dimension. Reshaping allows us to add or remove dimensions in an array.

Does reshape create a new array?

reshape() function is used to create a new array of the same size (as the original array) but of different desired dimensions. reshape() function will create an array with the same number of elements as the original array, i.e. of the same size as that of the original array.


1 Answers

As an alternative you might want to use System.Numerics.Tensors:

It makes reshaping very easy:

using System.Numerics.Tensors;
..
var src = new byte[3, w, h]
var dst = ArrayTensorExtensions
    .ToTensor(src)
    .Reshape(new[] { 3, w * h });
like image 194
koryakinp Avatar answered Sep 17 '22 14:09

koryakinp