首页 > 解决方案 > 计算二维 numpy 数组上移动窗口中整数的出现次数

问题描述

我想计算每个整数这个值在移动窗口中出现的频率。但是我不知道如何解决这个问题,因为我只能找到如何计算焦点平均值。

所以窗口的大小是:

kernel =array([[1, 1, 1],
               [1, 1, 1],
               [1, 1, 1]])

输入数据:

input = array([[3, 3, 2, 3],
               [3, 1, 2, 3],
               [2, 1, 1, 1],
               [3, 1, 3, 2]])

输出应如下所示:第一个“层”计数为 1,第二个“层”计数为 2,依此类推。

output = array([[[1, 1, 1, 0],
                 [2, 3, 4, 2],
                 [3, 4, 5, 3],
                 [2, 3, 4, 2]],
                [[0, 2, 2, 0],
                 [1, 3, 2, 2],
                 [1, 2, 2, 2],
                 [1, 1, 1, 1]],
                [[3, 3, 3, 2],
                 [3, 3, 3, 2],
                 [2, 3, 2, 2],
                 [1, 2, 1, 1]]])

输出应该是一个 3 维数组。x, y 是原始数组的维度,z 是唯一整数的数量。每层显示每个唯一整数的计数。

如果您对如何解决这个问题有任何指导,那就太好了。

标签: pythonarraysnumpycountscipy

解决方案


import numpy as np

def focal_lcz_count(image, window_w, window_h, int_val):

    w, h = image.shape
    count_arr = np.zeros([w, h])
    for i in range(w):
        for j in range(h):
            window = image[i:i+window_w, j:j+window_h]
            np.zeros([w, h])
            count_arr[i,j] = np.count_nonzero(window == int_val)

    return count_arr


def list_focal_count(input_array,integer_list, window_size):

    count_list = []
    for i, item in enumerate(integer_list):
        count_out = focal_lcz_count(image=input_array, window_w=window_size, window_h=window_size, int_val=item)
        count_out = count_out.flatten()
        count_list.append(count_out)
        raster_array = np.asarray(count_list)

    return count_list


input = np.random.randint(1, 4, ( 8, 8))
integ_list= [1,2,3]

result = list_focal_count(input_array=input,integer_list=integ_list, window_size=3)
print(result)

推荐阅读