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

使用numpy实现数组峰值检测时reshape出现维度不匹配问题

问题解答

错误原因

你确实移除了峰值对应的数据。代码中A = tiled_array[filt]使用布尔索引仅提取了filt为True的背景窗口元素,所有峰值窗口(filt为False)的元素被直接丢弃,导致最终数组元素总数少于原数组,无法reshape回原始尺寸。

修正方案

不要通过布尔索引筛选元素,直接在原维度上基于掩码赋值即可,全程保留数组形状,最后裁掉补的padding就能得到和原始输入尺寸一致的结果。

修正后代码

import numpy as np

def numpy_separation(transformed_2d, window_size_r, k, window_size_s=1):
    original_w = transformed_2d.shape[1]
    # 保留原边缘padding逻辑
    pad = np.zeros((transformed_2d.shape[0], 1)) + np.vstack(transformed_2d[:, -1])
    while transformed_2d.shape[1] % 2 != 0:
        transformed_2d = np.append(transformed_2d, pad, axis=1)

    img_h, img_w = transformed_2d.shape
    tiled_array = transformed_2d.reshape(img_h//window_size_s, window_size_s,
                                img_w//window_size_r, window_size_r)
    tiled_array = tiled_array.swapaxes(1,2)

    gamma = np.std(transformed_2d)
    # 计算每个窗口是否为背景窗口
    filt = np.ptp(tiled_array, axis=3) < k * gamma
    # 将掩码扩展到和tiled_array同维度,每个窗口内的所有元素共享同一个掩码值
    filt_expanded = np.repeat(filt[..., np.newaxis], window_size_r, axis=-1)
    # 峰值窗口位置直接设为0,保留背景值
    tiled_array[~filt_expanded] = 0
    # 还原为padding后的二维尺寸
    background_component = tiled_array.swapaxes(1,2).reshape(img_h, img_w)
    # 裁掉padding部分,恢复原始输入宽度
    background_component = background_component[:, :original_w]
    # 基于原始输入计算前景分量
    foreground_component = transformed_2d[:, :original_w] - background_component
    return background_component, foreground_component

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 00:36:11