反转数组结构
Invert structure of array
我有一个代表视频的数组。目前它的设置方式是第一个元素是第一个像素在所有不同时间步长的所有值的数组,然后第二个元素是第二个像素的,依此类推。我想要它,所以第一个元素将是第一个时间步所有像素的数组。
所以对于 2x2 视频的两帧,我想要
[
[
[a1, a2, a3], [b1, b2, b3]
],
[
[c1, c2, c3], [d1, d2, d3]
]
]
成为
[
[
[a1, b1],
[c1, d1]
],
[
[a2, b2],
[c2, d2]
],
[
[a3, b3],
[c3, d3]
],
]
我目前的实现是这样的:
def remap_image(seq):
# seq = np.array(seq)
s = seq.shape
a = np.zeros((s[2], s[0], s[1]))
for x, px in enumerate(tqdm(seq)):
for y, py in enumerate(px):
for p_counter, value in enumerate(py):
a[p_counter][x][y] = value/100.
return a
这按预期工作,但这种方法非常慢。有没有更快的方法来做到这一点?
您可以使用具有更好语义的 einops。
对于您的情况,以下简单代码有效。
from einops import rearrange
def remap_image(seq):
return rearrange(seq, 'w h t -> t w h')
按照 Mateen Ulhaq 所说的,简单地说
def remap_image(seq):
return seq.transpose(2, 0, 1)
我不确定它会快得多,但您可以使用 zip():
a = [
[
["a1", "a2", "a3"], ["b1", "b2", "b3"]
],
[
["c1", "c2", "c3"], ["d1", "d2", "d3"]
]
]
b = (list(map(list,zip(*r))) for r in a)
b = list(map(list,zip(*b)))
print(b)
[
[
['a1', 'b1'],
['c1', 'd1']
],
[
['a2', 'b2'],
['c2', 'd2']
],
[
['a3', 'b3'],
['c3', 'd3']
]
]
如果您的数据在 numpy 数组中,那么 b = np.transpose(a,axes=(2,0,1))
会直接且非常快速地完成。
我有一个代表视频的数组。目前它的设置方式是第一个元素是第一个像素在所有不同时间步长的所有值的数组,然后第二个元素是第二个像素的,依此类推。我想要它,所以第一个元素将是第一个时间步所有像素的数组。
所以对于 2x2 视频的两帧,我想要
[
[
[a1, a2, a3], [b1, b2, b3]
],
[
[c1, c2, c3], [d1, d2, d3]
]
]
成为
[
[
[a1, b1],
[c1, d1]
],
[
[a2, b2],
[c2, d2]
],
[
[a3, b3],
[c3, d3]
],
]
我目前的实现是这样的:
def remap_image(seq):
# seq = np.array(seq)
s = seq.shape
a = np.zeros((s[2], s[0], s[1]))
for x, px in enumerate(tqdm(seq)):
for y, py in enumerate(px):
for p_counter, value in enumerate(py):
a[p_counter][x][y] = value/100.
return a
这按预期工作,但这种方法非常慢。有没有更快的方法来做到这一点?
您可以使用具有更好语义的 einops。 对于您的情况,以下简单代码有效。
from einops import rearrange
def remap_image(seq):
return rearrange(seq, 'w h t -> t w h')
按照 Mateen Ulhaq 所说的,简单地说
def remap_image(seq):
return seq.transpose(2, 0, 1)
我不确定它会快得多,但您可以使用 zip():
a = [
[
["a1", "a2", "a3"], ["b1", "b2", "b3"]
],
[
["c1", "c2", "c3"], ["d1", "d2", "d3"]
]
]
b = (list(map(list,zip(*r))) for r in a)
b = list(map(list,zip(*b)))
print(b)
[
[
['a1', 'b1'],
['c1', 'd1']
],
[
['a2', 'b2'],
['c2', 'd2']
],
[
['a3', 'b3'],
['c3', 'd3']
]
]
如果您的数据在 numpy 数组中,那么 b = np.transpose(a,axes=(2,0,1))
会直接且非常快速地完成。