Pythonで図形の輪郭の大きさを調べる(OpenCV編)
PythonのOpenCV(cv2)モジュールで描いた図形の輪郭の大きさを調べます。
目次
輪郭が占める面積の計算方法
PythonのOpenCV(CV2)モジュールでfindContoursを使うと図形の輪郭が得られます。具体的な方法は 別の投稿 を参照してください。
この輪郭の内側の面積は、contourAreaメソッドで計算できます。
retval = cv2.contourArea(contour, [oriented])
変数 |
型 |
内容 |
---|---|---|
contour |
ndarray |
輪郭のデータ。 |
oriented |
bool |
省略可。既定値はFalse。方向性を有効にするかどうか。 |
retval |
float |
輪郭が占める面積。 |
方向性についてはよくわかりません。
計算の実施例
この画像から全ての輪郭を抽出して、それぞれの面積を計算してみます。

コードはこんな感じです。
import cv2
im = cv2.imread('test.png')
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
retval, im_bw = cv2.threshold(im_gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
# 輪郭の検出
contours, hierarchy = cv2.findContours(im_bw, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# 輪郭を1つずつ書き込んで出力
for i in range(len(contours)):
im_con = im.copy()
print('ID', i, 'Area', cv2.contourArea(contours[i]))
im_con = cv2.drawContours(im_con, contours, i, (0,255,0), 2)
cv2.imwrite('result' + str(i) + '.png', im_con)
出力はこうなります。

ID 0 Area 718.0

ID 1 Area 5350.5

ID 2 Area 2.0

ID 3 Area 2.0

ID 4 Area 5755.5

ID 5 Area 14848.0

ID 6 Area 308.0

ID 7 Area 622.0

ID 8 Area 5110.5

ID 9 Area 7916.0
実用的には、面積が極端に小さいのを取り除くと使いやすそうです。
公開日
広告
Pythonで画像処理カテゴリの投稿
- Python (Pillow)でグラデーション画像を作る
- PythonでGIFアニメを作る(PILでファイルをつなげる編)
- PythonでOpenCVの画像データをMatplotlibで表示する
- PythonでPDFを画像に変換する(Windows10)
- PythonでPSDファイルをJPEGやPNGに変換する
- Pythonでカラー画像をグレイスケールに変換する(OpenCV編)
- Pythonでフォルダ内に同じ画像がないか検索してみた
- Pythonでマスク画像を作る方法(3選)
- Pythonで図形の外接矩形を描く(OpenCV編)
- Pythonで図形の輪郭の大きさを調べる(OpenCV編)
- Pythonで画像の余白を削除する(OpenCV編)
- Pythonで画像の余白を削除する(Pillow編)
- Pythonで画像の大きさやフォーマットを調べる(Pillow編)
- Pythonで画像の減色をする
- Pythonで画像をトリミングする(Pillow編)
- Pythonで画像を他の画像にペーストする(Pillow編)
- Pythonで画像を回転する(Pillow編)
- Pythonで画像を拡大縮小(リサイズ)する(Pillow編)
- Pythonで画像を読み込み、表示し、保存する(OpenCV編)
- Pythonで画像を読み込み、表示し、保存する(Pillow編)
- Pythonで画像を2値化する(OpenCV編)
- Pythonで記号の輪郭を検出する(OpenCV編)
- PythonとOpenCVで画像をグレースケールに変換してみた
- PythonとOpenCVで画像をネガポジ反転してみた