画像の上端・くびれの座標取得
PythonのOpenCVを用いて、画像の解析を試みています。
上の輪郭画像(sample.jpg)から、マークした上端(赤丸)と、くびれ部分の頂点(青丸)の座標を取得したいのですが、調べても方法が分かりません。
こちらのサイトに載っていた端点、凸性欠陥の検出のコードを試してみましたが、うまくいきませんでした。
コードは以下の通りです。
python
1import cv2 2 3img = cv2.imread("sample.jpg") 4gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 5 6ret, thresh = cv2.threshold(gray, 127, 255,0) 7contours = cv2.findContours( 8 thresh, 9 cv2.RETR_EXTERNAL, 10 cv2.CHAIN_APPROX_SIMPLE)[0] 11 12#上端 13contours = contours[0] if len(contours)==2 else contours[1] 14c = max(contours, key = cv2.contourArea) 15top = tuple(c[c[:, :, 1].argmin()][0]) 16#凸性欠陥 17cnt = contours[0] 18hull = cv2.convexHull(cnt,returnPoints=False) 19defects = cv2.convexityDefects(cnt,hull) 20 21for i in range(defects.shape[0]): 22 s,e,f,d = defects[i,0] 23 start = tuple(cnt[s][0]) 24 end = tuple(cnt[e][0]) 25 far = tuple(cnt[f][0]) 26 cv2.line(img,start,end,[0,255,0],2) 27 cv2.circle(img,far,5,[0,0,255],-1) 28
このあと上端や凸性欠陥がマークアップされた画像を表示しようとしているのですが、その前にそれぞれ、以下のようなエラーが出てしまいます。
発生している問題・エラーメッセージ
python
1#上端 2Traceback (most recent call last): 3 File "<stdin>", line 1, in <module> 4IndexError: too many indices for array 5 6#凸性欠陥 7Traceback (most recent call last): 8 File "<stdin>", line 1, in <module> 9AttributeError: 'NoneType' object has no attribute 'shape'
該当のソースコード
python
1#上端 2top = tuple(c[c[:, :, 1].argmin()][0]) 3 4#凸性欠陥 5for i in range(defects.shape[0]):
試したこと
凸性欠陥については、
python
1defects is None
の戻り値がTrueとなったため、defectsに値が格納できていないようです。ただ、どうすれば改善できるのか分かりません。
コードが正常に動くような、或いは全く別の方法でもいいので上端・くびれ頂点の座標取得についてのアドバイスを頂ければと思います。
詳しい方、よろしくお願いします。
補足情報(FW/ツールのバージョンなど)
Python 2.7.17
OpenCV 4.1.2.30
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/12 07:29
2020/01/12 09:06
2020/01/14 00:49