Python实现800x800图像分块100x100后拼接失败问题求助
Hey there! Let's break down why your stitched image is coming out wrong and fix it step by step.
What's Wrong With Your Current Reconstruction Code?
Your approach to rebuilding the image by grabbing individual rows from each block and stacking them is misordered. Right now, you're stacking all the 0th rows from every block first, then all the 1st rows, and so on. This creates a 6400x100 array instead of the 800x800 you need, and the spatial arrangement of the blocks is completely off.
Additionally, your index calculation has a small flaw: when accessing main2_array, you're treating it as a 1D array, but after your block-storage step, it's actually a 2D array (64 rows, each holding a flattened 100x100 block).
The Correct Way to Stitch Blocks Back Together
Instead of looping through individual rows, we'll:
- Reshape each flattened block back into a 100x100 matrix.
- Stitch blocks horizontally first to form each 800x100 row of the original image.
- Stitch those rows vertically to get the full 800x800 image.
Fixed Reconstruction Code
Replace your problematic拼接图像块 section with this:
# Reshape the stored blocks back to (64, 100, 100) blocks = main2_array.reshape(64, 100, 100) # Split blocks into 8 rows (each with 8 blocks), stitch each row horizontally image_rows = [] for row_idx in range(8): # Grab 8 blocks for the current row row_blocks = blocks[row_idx*8 : (row_idx+1)*8] # Stitch them horizontally to make an 800x100 row stitched_row = np.hstack(row_blocks) image_rows.append(stitched_row) # Stitch all rows vertically to get the full 800x800 image reconstructed_image = np.vstack(image_rows) # Verify the shape (should be (800, 800)) print(reconstructed_image.shape)
Bonus: Simplify Your Block Storage Code
While you said this part works, we can clean it up to be more efficient and readable (no need for initial zeros and deletion):
# Initialize an array to hold 64 flattened 100x100 blocks main2_array = np.zeros((64, 10000)) block_idx = 0 for row in tqdm_notebook(range(0, 8)): for col in range(0, 8): # Extract the 100x100 block, flatten it, and store it block = image_array[row*100 : (row+1)*100, col*100 : (col+1)*100].flatten() main2_array[block_idx] = block block_idx += 1
This avoids the vstack and delete steps which can be slow and error-prone.
内容的提问来源于stack exchange,提问作者Engineman

