简体   繁体   中英

Count occurrences of integers in moving window on 2-dimensional numpy array

I would like to calculate per integer how often this value occurs within a moving window. I have no idea however how to tackle this as I can only find how to calculate a focal mean.

So the window has the size:

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

The input data:

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

The output should look like the following: First "layer" count of 1, Second "layer" count of 2 etc.

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]]])

The output should be a 3 dimensional array. x, y the dimensions of the original array, and z the amount of unique integers. Each layer shows the count per unique integer.

if you have any directions on how to solve this that would be great.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM