简体   繁体   中英

How to turn 3D image matrix to 2d matrix without a for loop? Python and numpy

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

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

data_2d = data_3d.swapaxes(1,2).reshape(3,-1)
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)
>>> 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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM