LoginSignup
2
1

More than 1 year has passed since last update.

OpenCVを使って緑被を抽出する

Last updated at Posted at 2021-09-08

Pythonで使えるライブラリの1つとしてOpenCVがありますが、活用例として特定の色の抽出がよく紹介されます。
今回は、OpenCVと緑被分布図を使って、駅から半径1.5km以内の範囲にある緑被の抽出・緑被率の計算を行うプログラムを作成してみました。

緑被分布図の準備

緑被分布図は下記のリンクから。
首都圏と近畿圏のものがあるようです。

緑被分布図の公開 - 大都市圏整備(国土交通省)
https://www.mlit.go.jp/crd/daisei_ryokuhi_index.html

駅から半径1.5km以内の範囲を示す緑被分布図の作成

現時点では気合いで作成します(いずれは自動化していきたい…)。
例えば新宿駅なら次のような図になります。
shinjuku.jpg

コード

下記のサイトを参考に、コードを書いてみました。

OpenCV 入門 (10) - 色の抽出
https://note.com/npaka/n/nc6764b99dbe0

【Python+OpenCV】特定の色を検出するプログラム
https://craft-gogo.com/python-opencv-color-detection/

今回は「緑被地(主に樹林地)」・「緑被地(主に草地)」の2種類を抽出します。

import cv2
import numpy as np

#パスを指定
path = ""  #適宜パスを指定する

#駅を指定
station = "shinjuku"  #上記パスの下に作成した円形の緑被分布図を置き、駅名を付けて保存しておく

#画像の読み込み
img = cv2.imread(f'{path}{station}.jpg')

#周囲の余白を除去・計測・図示
img_array = np.asarray(img)
white_min = np.array([235, 235, 235])
white_max = np.array([255, 255, 255])
mask_white = cv2.inRange(img, white_min, white_max)
cv2.imwrite(f'{path}white_mask_{station}.png', mask_white)
white_array = np.asarray(mask_white)
white_count = np.count_nonzero(white_array == 255)

#HSVに変換
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# 緑色のHSVの値域
hsv_min = np.array([30, 64, 0])
hsv_max = np.array([90, 255, 255])
mask = cv2.inRange(hsv, hsv_min, hsv_max)
masked_img = cv2.bitwise_and(img, img, mask = mask)

#緑色のピクセル範囲を図示
cv2.imwrite(f'{path}green_mask_{station}.png', mask)
cv2.imwrite(f'{path}green_masked_img_{station}.png', masked_img)

#緑色のピクセル比率を算出
hsv_array = np.asarray(mask)
chi = np.count_nonzero(hsv_array == 255)
mot = np.count_nonzero(hsv_array > -1) - white_count
prob = chi / mot * 100

print(prob, "%")

出力

white_mask_shinjuku.png
余白の判定図

green_mask_shinjuku.png
緑被の判定図

green_masked_img_shinjuku.png
緑被の抽出図

緑被率は下記の通り。

10.700869741784832 %

参考文献

緑被分布図の公開 - 大都市圏整備(国土交通省)
https://www.mlit.go.jp/crd/daisei_ryokuhi_index.html

OpenCV 入門 (10) - 色の抽出
https://note.com/npaka/n/nc6764b99dbe0

【Python+OpenCV】特定の色を検出するプログラム
https://craft-gogo.com/python-opencv-color-detection/

2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1