You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

滑动窗口提取图像保存至3D矩阵时报错,求排查解决

Fixing the Sliding Window Saving Error in Your Code

Let's walk through the issues causing errors in your code and how to resolve them:

1. Primary Issue: Index Out-of-Bounds

You initialized matrix A with a fixed size of (100, winW, winH), but the number of sliding windows generated by your pyramid and sliding window loops will almost certainly exceed 100. When the variable b increments to 101, trying to assign to A[b,:,:] will throw an index error—since Python uses 0-based indexing, A only accepts indices from 0 to 99 for its first dimension.

Additionally, starting with b=1 wastes the first position (A[0,:,:]) and makes you hit the index limit even faster.

2. Secondary Issue: Potential Data Type Mismatch

np.empty() creates an array with a default float64 data type, but your window is a grayscale image slice stored as uint8 (integer values 0-255). Directly assigning uint8 values to a float64 array can lead to unnecessary type conversions or unexpected behavior.

Instead of preallocating a fixed-size matrix (which requires knowing the exact number of windows upfront), use a Python list to dynamically collect all valid windows, then convert it to a 3D numpy array once you're done. This avoids index errors entirely and handles any number of windows.

Modified Code Snippets:

Replace your matrix initialization section:

# Replace fixed-size matrix with a dynamic list
windows_list = []

Then, in the sliding window loop, replace the problematic lines with:

# Add the valid window to our list
windows_list.append(window)

After processing all windows, convert the list to a 3D numpy array:

# Convert the list to a 3D matrix (shape: [number_of_windows, winH, winW])
A = np.array(windows_list)
# Verify the shape (optional)
print(f"Final shape of matrix A: {A.shape}")

Alternative: Preallocate a Fixed-Size Matrix (If You Need It)

If you must use a preallocated matrix, first calculate the exact number of valid windows to set the correct size:

# First, count all valid windows
window_count = 0
for resized in pyramid(image, scale=2):
    for (x, y, window) in sliding_window(resized, stepSize=32, windowSize=(winW, winH)):
        if window.shape[0] != winH or window.shape[1] != winW:
            continue
        window_count += 1

# Initialize matrix with matching size and data type
A = np.empty((window_count, winH, winW), dtype=window.dtype)
b = 0  # Start at 0 for 0-based indexing

Then in the loop:

A[b,:,:] = window
b += 1

This ensures you never exceed the matrix bounds and matches the data type of your windows.

内容的提问来源于stack exchange,提问作者Aros

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:45:03