Flattening inner dimensions

Viewed 80

I have matrix (image data) of size (209, 64, 64, 3). As this is image data, in order to input the matrix into a Neural Network. I need to flatten the inner 3 dimensions (2,3,4) into a single (64 x 64 x 3 = 12288) column vector. So the final matrix will be of dimensions (12288, 209)

How could I achieve this,

# I am able to flatten the entire matrix using `Iterators.flatten()` function but no clue how to flatten just the inner 3 dimensions.

a = rand(209,64,64,3)
a_flat = Iterators.flatten(a) |> collect

size(a_flat)
#Out > (2568192,)

Also does anyone know if the color channels in pixels must be, all red band first for all pixels of images followed by blue and green (in the format [r; r; r; r ... b; b; b; b; ... g; g; g; g]).

Or could it be in the form r,g,b of the first pixel, then r,g,b of the next pixel and so on (in the form [r; b; g; r; ... g; r; b; g]). Here I used the semicolon (;) just to show that its a column vector rather than row vector

1 Answers

I have come up with following piece of code, but there must be a better way to do this.

a = rand(209,64,64,3)
m = Array{Float64}(undef, (size(a)[2]*size(a)[3]*size(a)[4],size(a)[1]))

for i = 1:size(a)[1]
    m[:, i] = Iterators.flatten(a[i,:,:,:]) |> collect 
end 

size(m)
# Out > (12288, 209)
Related