2

Currently working on a lab from a Data course at school. What I want to do is convert matrix_a with shape (26,64,64) to a new matrix_b (64,1664). The (64,64) inside matrix_a is the bits that make up a series of images, and the (64,1664) matrix_b should result in a strip of the images. I tried using np.reshape, which does reshape the matrix correctly, but the images are lost due to the ordering used. I could use a for loop to iteratively insert each 64x64 image into matrix_b, yet they're asking that you do not use a for loop. They mentioned something about using splicing? I'm writing this in python with numpy. Apologies if this post makes no sense it's my first one. Thanks

3 Answers3

1

With numpy, you can try this (assume data_3d is your 3d array):

data_2d = data_3d.swapaxes(1,2).reshape(3,-1)
ldren
  • 159
  • 5
0
import numpy as np
arr = np.random.randint(10, size= [26,64,64])
arr.shape

>>> (26, 64, 64)

transpose() reorders axes from [0, 1, 2] to [1, 0, 2].

arr = arr.transpose([1,0,2])   # edit suggested by @wwii 
arr.shape

>>> (64, 64, 26)
arr = arr.reshape([64, -1])
arr.shape

>>> (64, 1664)
hammi
  • 804
  • 5
  • 14
  • OP wants a 2d array with the 26 64x64 images *concatenated*. – wwii Aug 08 '20 at 18:20
  • @wwii "and the (64,1664) matrix_b should result in a strip of the images" exact words of OP – hammi Aug 08 '20 at 18:21
  • The shape might be correct but does the data come out correct? Try it with (4,3,3) array - `a = np.arange(3*3*4).reshape(4,3,3)`. – wwii Aug 08 '20 at 18:41
  • 1
    `arr..transpose([1,0,2])` looks better. – wwii Aug 08 '20 at 18:59
  • @wwii yeah the `transpose()` takes care of that. OP wasnt specific about how he wanted to strip data column wise or row wise, thus two options for `transpose()` – hammi Aug 08 '20 at 20:11
0
>>> a = np.arange(2*2*3).reshape(3,2,2)
>>> a
array([[[ 0,  1],
        [ 2,  3]],

       [[ 4,  5],
        [ 6,  7]],

       [[ 8,  9],
        [10, 11]]])

Concatenate each image.

Horizontal strip - which is what you asked for in the question.

>>> np.concatenate(list(a),-1)
array([[ 0,  1,  4,  5,  8,  9],
       [ 2,  3,  6,  7, 10, 11]])

Vertical strip

>>> np.concatenate(list(a),0)
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11]])
>>>

np.hstack(tuple(a)) and np.vstack(tuple(a)) produce identical results to concatenate.

np.vsplit(a,a.shape[0]) is equivalent to list(a) or tuple(a).

wwii
  • 23,232
  • 7
  • 37
  • 77