2017-02-19 16 views
2

私はcv2.findContoursから得られたNumPy配列contoursを持っていて、contours = np.concatenate(contours, axis = 0)を使って平らにしました。画像からのオブジェクトの輪郭の座標を格納します。ただし、XまたはYのいずれか小さい方の座標を削除する場合は、100、または1000を超えています。最初にcontours = np.delete(contours, 0)contours = np.delete(contours[0], 0)を使用してすべての項目を削除しようとしましたが、このエラーが発生しました: IndexError: invalid index to scalar variable.NumPy配列から値のペアを削除します

このような値のペアを削除するにはどうすればよいですか?

print(type(contours)) 
→ <class 'numpy.ndarray'> 
print(contours[0]) 
→ [[2834 4562]] 
print(type(contours[0])) 
→ <class 'numpy.ndarray'> 
print(contours[0][0]) 
→ [2834 4562] 
print(type(contours[0][0])) 
<class 'numpy.ndarray'> 

はまた、私はそれが私がcv2.convexHull(contours)に送信することを必要とする形で正確だから、それ以上のリストを/連結平らにする必要はありません。

はここに私のコードの最小限の作業のサンプルです:ここで

import cv2   # library for processing images 
import numpy as np # numerical calculcations for Python 

img = cv2.imread("img.png") 
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 
_, img_thr = cv2.threshold(img_gray,0,255,cv2.THRESH_OTSU) 
img_rev = cv2.bitwise_not(img_thr) 
img_cnt, contours, hierarchy = cv2.findContours(img_rev, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 
contours = np.concatenate(contours, axis = 0) 

hull = cv2.convexHull(contours) 
rect = cv2.minAreaRect(np.int0(hull)) 
box = cv2.boxPoints(rect) 
box = np.int0(box) 

img_cnt = cv2.drawContours(img, contours, -1, (0,255,0), 3) 
img_cnt = cv2.drawContours(img, [box], -1, (0,0,255), 5) 

cv2.imwrite("img_out.png", img_cnt) 

はサンプルinput imageあり、ここで私のoutput imageです。私は、テキスト選択のための外側の "ノイズ"を無視したい。私はさらなるノイズ削減を使用することはできません。

+1

[最小、完全、および確認可能](http://stackoverflow.com/help/mcve)の例を作成してください。そうすれば、私たちがあなたを助けやすくなります。 –

答えて

2

contours.shapeは(N、1,2)と思われます。この場合、

contours[((contours>100)&(contours<1000)).all(axis=(1,2))] 

となります。例による

In [106]: contours=randint(0,1100,(10,1,2)) 
[[[ 803 772]] 
[[ 210 490]] 
[[ 433 76]] 
[[ 347 88]] 
[[ 763 747]] 
[[ 678 200]] 
[[ 816 444]] 
[[ 528 817]] 
[[ 140 440]] 
[[1019 654]]] 

In [108]: valid = ((contours>100)&(contours<1000)).all(axis=(1,2)) 
Out[108]: array([ True, True, False, False, True, True, 
        True, True, True, False], dtype=bool) 

In [111]: contours[valid] 
Out[111]: 
array([[[803, 772]], 
     [[210, 490]], 
     [[763, 747]], 
     [[678, 200]], 
     [[816, 444]], 
     [[528, 817]], 
     [[140, 440]]]) 

あなたはXとYの上に別のクリップをしたい場合は、代わりに

(contours>[xmin,ymin])&(contours<[xmax,ymax]) 

を使用することができます。

+0

解決と説明をありがとう。今の魅力のように動作します:) – MrVocabulary

+0

私は自分自身に短いフォローアップの質問を許します:もし私が各軸ごとに異なる閾値を設定したいのであれば?私が理解しているように、all()には繰り返しが必要です。 – MrVocabulary

+1

このケースの投稿を編集します。 –

関連する問題