パイクラおじさんの日記

MinecraftでPythonを勉強するおじさんの日記です。

物体の数を数える(池)

DEM構成点種別マップでこのページの「物体の数を数える」を試した。

f:id:pycra:20170923195846p:plain

プログラム

物体として認識されるサイズとして3種類を試した結果を表示するようにした。

buttai.pyとして作成。

# coding: utf-8

import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage
import sys


NPY_DIR = "/Users/pycra/Desktop/NPY_DATA"

if len(sys.argv) < 2:
    print("buttai.py npyfilename")
    exit(-1)

array = np.load(NPY_DIR+"/"+sys.argv[1])
array = 1 * (array == 3)    # 3=内水面

im_open = scipy.ndimage.binary_opening(array, np.ones((3, 3)), iterations=2)
label3, num_features = scipy.ndimage.measurements.label(im_open)
print("label3=", label3)
print("num_features=", num_features)

im_open = scipy.ndimage.binary_opening(array, np.ones((2, 2)), iterations=2)
label2, num_features = scipy.ndimage.measurements.label(im_open)
print("label2=", label2)
print("num_features=", num_features)

im_open = scipy.ndimage.binary_opening(array, np.ones((1, 1)), iterations=2)
label1, num_features = scipy.ndimage.measurements.label(im_open)
print("label1=", label1)
print("num_features=", num_features)

plt.subplot(221)
plt.imshow(array, cmap='Greys_r')
plt.colorbar()
plt.subplot(222)
plt.imshow(label3, cmap='Greys_r')
plt.colorbar()
plt.subplot(223)
plt.imshow(label2, cmap='Greys_r')
plt.colorbar()
plt.subplot(224)
plt.imshow(label1, cmap='Greys_r')
plt.colorbar()
plt.show()

実行結果

$ python buttai.py npysurf-5340-22-12.npy
label3= [[0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 ..., 
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]]
num_features= 2
label2= [[0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 ..., 
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]]
num_features= 4
label1= [[0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 ..., 
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]]
num_features= 3

f:id:pycra:20170923222409p:plain

label配列には見つかった物体毎に1, 2, 3…と値が入るらしい。

Pythonメモ

しかし、2値化するための処理が次の1行でできるってのが凄い。

Python言語の機能なのか?NumPyの機能なのか?

array = 1 * (array == 3)    # 3=内水面

複数のグラフを1つにまとめる

naoyura.github.io

subplotがミソ。