[英]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).我想要做的是将具有形状(26,64,64)的matrix_a转换为新的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. matrix_a 中的 (64,64) 是组成一系列图像的位,而 (64,1664) matrix_b 应该生成图像条。 I tried using np.reshape, which does reshape the matrix correctly, but the images are lost due to the ordering used.我尝试使用 np.reshape,它确实正确地重塑了矩阵,但由于使用的排序,图像丢失了。 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.我可以使用 for 循环将每个 64x64 图像迭代地插入到 matrix_b 中,但他们要求您不要使用 for 循环。 They mentioned something about using splicing?他们提到了一些关于使用拼接的东西? I'm writing this in python with numpy.我在 python 和 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):使用 numpy,您可以试试这个(假设 data_3d 是您的 3d 阵列):
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]
. transpose()
轴从[0, 1, 2]
重新排序为[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.hstack(tuple(a))
和np.vstack(tuple(a))
产生与concatenate
相同的结果。
np.vsplit(a,a.shape[0])
is equivalent to list(a)
or tuple(a)
. np.vsplit(a,a.shape[0])
等价于list(a)
或tuple(a)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.