如何将形状为(20,10,56,56,3)的NumPy帧序列水平拼接?
Ah, I see the issue here—your initial reshape isn't working because it's just rearranging elements in memory order, not actually stitching the frames together horizontally like you want. Let's break down why that happens and fix it properly.
Why Your Original Reshape Failed
When you run np.reshape(img_array, (20,56,560,3)), NumPy uses C-style (row-major) ordering to reorder elements. Your original array is structured as (batch, num_frames, height, width, channels), so the memory layout flows like this: first batch item → first frame → first row of that frame → all pixels in that row → next row, etc. Reshaping directly would mash together rows from different frames instead of placing entire frames side by side, hence the "row chaos" you're seeing.
Solution 1: Transpose + Reshape (Most Efficient)
The cleanest and fastest way to get the correct horizontal stitch is to adjust the dimension order first, then reshape. This avoids unnecessary data copying and leverages NumPy's efficient array view operations:
- Transpose the array to move the
num_framesdimension (index 1) right after theheightdimension (index 2). This rearranges the structure to(batch, height, num_frames, width, channels)—so for each batch item, we have 56 rows, each with 10 blocks of 56-pixel-wide columns. - Reshape to merge the
num_framesandwidthdimensions into a single 560-pixel width. Since the dimensions are now ordered correctly, reshaping won't mess up frame alignment.
import numpy as np # Assuming your array is img_array with shape (20, 10, 56, 56, 3) transposed = img_array.transpose(0, 2, 1, 3, 4) # Shape becomes (20, 56, 10, 56, 3) result = transposed.reshape(20, 56, 10 * 56, 3) # Final shape (20, 56, 560, 3)
Solution 2: np.hstack (More Intuitive)
If you prefer a simpler, easier-to-read approach (slightly less efficient for large datasets), you can use np.hstack to stitch each batch's frames together horizontally. hstack is designed for exactly this use case—it combines arrays along their width axis (axis 1):
# Iterate over each batch item, hstack its 10 frames result = np.array([np.hstack(frames) for frames in img_array])
Each frame in frames is (56,56,3), so stacking them along axis 1 produces a (56, 560, 3) array per batch item, which is exactly what you need.
Final Note
Both methods will give you the desired (20,56,560,3) array. The transpose+reshape method is better for performance with large datasets, while hstack is more straightforward to understand at a glance.
内容的提问来源于stack exchange,提问作者konstantin

