更改强制执行给定值的numpy数组的结构 [英] Changing structure of numpy array enforcing given value

查看:74
本文介绍了更改强制执行给定值的numpy数组的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果具有2 * 2像素的任何元素包括1,否则如何将4 X 6大小的栅格数据缩小为2 X 3大小以强制选择"1"?

How can I downscale the raster data of 4 X 6 size into 2 X 3 size enforcing '1' to be chosen if any element with in 2*2 pixels include 1, otherwise 0?

import numpy as np
data=np.array([
[0,0,1,1,0,0],
[1,0,0,1,0,0],
[1,0,1,0,0,0],
[1,1,0,0,0,0]])

结果应为:

result = np.array([
    [1,1,0],
    [1,1,0]])

推荐答案

您可以使用scikit learning的补丁程序提取例程,如下所示(您应该能够复制并粘贴):

You could use the patch extraction routine of scikit learn as follows (you should be able to copy and paste):

from sklearn.feature_extraction.image import extract_patches

data = np.array([[0, 0, 1, 1, 0, 0],
                 [1, 0, 0, 1, 0, 0],
                 [1, 0, 1, 0, 0, 0],
                 [1, 1, 0, 0, 0, 0]])

patches = extract_patches(data, patch_shape=(2, 2), extraction_step=(2, 2))
non_zero_count_patches = (patches > 0).any(axis=-1).any(axis=-1).astype(int)
print non_zero_count_patches

说明:函数extract_patches在您的数组上生成一个视图,该视图表示大小为patch_shape和离散化步骤extraction_step的滑动补丁,您可以根据需要进行更改.下面的行检查哪个补丁包含非零项目.但是,这可以用您可能感兴趣的其他任何方式代替,例如均值,总和等.优点是您可以自由选择补丁大小和提取步骤(它们不需要对应),而无需占用内存,直到any被调用(它在内部使用步幅).

Explanation: the function extract_patches generates a view on your array that represents sliding patches of size patch_shape and of discretization step extraction_step, which you can vary as you want. The following line checks which of the patches contains a non zero item. However, this can be replaced by anything else you may be interested in, such as the mean, sum, etc. An advantage is that you can choose patch size and extraction step freely (they do not need to correspond), without memory overhead until any is invoked (it uses strides internally).

这篇关于更改强制执行给定值的numpy数组的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆