python二维矩阵求二维移动窗口内极大值的坐标
时间: 2023-04-02 13:04:45 浏览: 263
二维坐标系下求极大值
可以使用numpy库中的函数numpy.lib.stride_tricks.as_strided来实现二维移动窗口的操作,具体实现可以参考以下代码:
import numpy as np
def max_in_window(matrix, window_size):
# 计算窗口的步长
stride = matrix.strides
stride = (stride[], stride[1], stride[], stride[1])
# 利用as_strided函数生成移动窗口的视图
window_view = np.lib.stride_tricks.as_strided(matrix, shape=(
matrix.shape[] - window_size + 1, matrix.shape[1] - window_size + 1, window_size, window_size), strides=stride)
# 计算每个窗口内的最大值的坐标
max_index = np.unravel_index(np.argmax(window_view, axis=(2, 3)), (window_view.shape[], window_view.shape[1]))
# 将坐标转换为在原矩阵中的位置
max_index = np.array(max_index).T
max_index[:, ] += window_size // 2
max_index[:, 1] += window_size // 2
return max_index
# 测试代码
matrix = np.random.randint(, 10, size=(5, 5))
print(matrix)
print(max_in_window(matrix, 3))
阅读全文