File tree Expand file tree Collapse file tree
opencv/image/segmentation Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # -*- coding:utf-8 -*-
2+ import numpy as np
3+ import cv2
4+
5+ def main ():
6+ im = cv2 .imread ("test.jpg" ) # 入力画像の取得
7+ gray = cv2 .cvtColor (im ,cv2 .COLOR_BGR2GRAY ) # グレースケール変換
8+ th = cv2 .threshold (gray ,0 ,255 ,cv2 .THRESH_BINARY_INV + cv2 .THRESH_OTSU )[1 ] # 2値化
9+ k = np .ones ((3 ,3 ),np .uint8 ) # カーネルの定義
10+ bg = cv2 .dilate (th ,k ,iterations = 3 ) # 背景領域の抽出
11+ trans = cv2 .distanceTransform (bg ,cv2 .DIST_L2 ,3 ) # 背景領域の距離変換
12+ fg = cv2 .threshold (trans ,0.1 * trans .max (),255 ,0 )[1 ] # 距離変換した画像データを2値化して前景領域を抽出
13+ fg = np .uint8 (fg ) # 未知の領域を検索
14+ unknown = cv2 .subtract (bg ,fg )
15+ marker = cv2 .connectedComponents (fg )[1 ] # ラベリング処理
16+ marker = marker + 1
17+ marker [unknown == 255 ] = 0 # 未知領域を0で塗り潰す
18+ marker = cv2 .watershed (im ,marker ) # watershed法で領域分割
19+ im [marker == - 1 ] = [0 ,255 ,0 ] # 領域の境界(-1)を緑色でり潰
20+ cv2 .imshow ("watershed" ,im ) # 画像の表示
21+ cv2 .waitKey (0 ) # キー入力待機
22+ cv2 .destroyAllWindows () # ウィンドウ廃棄
23+
24+
25+ if __name__ == "__main__" :
26+ main ()
You can’t perform that action at this time.
0 commit comments