python - 计算二维 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 是唯一整数的数量。每层显示每个唯一整数的计数。
如果您对如何解决这个问题有任何指导,那就太好了。
解决方案
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)
推荐阅读
- angular - Angular - 如何消除电话抖动?
- c# - “BotAuthenticator 无法验证传入请求!” 使用 Bot 时 Teams 中的错误
- java - 如何在 Java 中使用“Starts with”变量查找文件
- facebook - 如何提交测试 Facebook 应用以供审核
- javascript - 我可以从任何文件中访问 html 元素 ID 吗?
- python - 使用 Python 执行 SoapUI API 调用
- python - 将 numpy 数组乘以大型 numpy packedbit 数组
- c# - 如何在不调用 MVC 中的数据库的情况下实现跨页面的搜索?
- html - 在 ionic 中打印来自 REST api 的 JSON 响应
- r - 使用 ggparcood() 绘制平行坐标图(GGally 包)