Sum of the cells around a single cell in a matrix with python – StackOverflow
隣接セルの足し合わせは要はコンボリューション.
元の配列が0/1なので,それをインデックスにすれば期待する出力になりそう.
import numpy as np from scipy import signal arr = np.array( [ [0, 0, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 0, 0, 0], [1, 1, 1, 0, 1, 1, 0, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0] ] ) kernel = np.ones((3, 3), dtype=np.int8) np.where(arr, signal.convolve(arr, kernel, 'same'), 0)
array([[0, 0, 0, 0, 0, 4, 4, 0, 0, 0],
[0, 0, 0, 0, 0, 6, 6, 0, 0, 0],
[2, 4, 4, 0, 6, 6, 0, 3, 0, 0],
[0, 0, 6, 8, 8, 7, 0, 3, 0, 0],
[0, 0, 4, 7, 7, 6, 4, 0, 0, 0],
[0, 0, 0, 0, 4, 0, 0, 0, 0, 0]])
10×10にするのも簡単.
kernel = np.ones((10, 10), dtype=np.int8) np.where(arr, signal.convolve(arr, kernel, 'same'), 0)
array([[ 0, 0, 0, 0, 0, 20, 19, 0, 0, 0],
[ 0, 0, 0, 0, 0, 21, 20, 0, 0, 0],
[11, 16, 19, 0, 21, 21, 0, 19, 0, 0],
[ 0, 0, 19, 21, 21, 21, 0, 19, 0, 0],
[ 0, 0, 19, 21, 21, 21, 20, 0, 0, 0],
[ 0, 0, 0, 0, 21, 0, 0, 0, 0, 0]])
ピンバック: 隣接カウント | 粉末@それは風のように (日記)
ピンバック: 隣接セルの合計(コンボリューション) | 粉末@それは風のように (日記)
ピンバック: 2次元配列で同じ値を持つ隣接要素を見つける – 配列内のフィーチャにラベル付け(Flood fill) | 粉末@それは風のように (日記)