2017-01-03 8 views
1

画像から赤色を検出し、画面サイズに基づいて座標を取得する必要がありました。マスクを使用pythonでopencvを使ったブロブフィルタリング

  • は赤色
  • を有する画像の一部がそれに
  • アプライドガウシアンフィルタをBWにそれを変換さフェッチ。

最終イメージには、残りの座標を削除して取得するために必要な小さなボディがあります。私はSimpleBlobDetectorを試しましたが、助けにはなりませんでした。これは私のコードです -

import cv2 
import numpy as np 
from PIL import Image 

img=cv2.imread("D:\Ankur\Free\line.png") 
img_hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV) 


lower_red = np.array([0,50,50]) 
upper_red = np.array([10,255,255]) 
mask0 = cv2.inRange(img_hsv, lower_red, upper_red) 


lower_red = np.array([170,50,50]) 
upper_red = np.array([180,255,255]) 
mask1 = cv2.inRange(img_hsv, lower_red, upper_red) 


mask = mask0+mask1 


output_img = img.copy() 
output_img[np.where(mask==0)] = 0 


gray = cv2.cvtColor(output_img, cv2.COLOR_BGR2GRAY) 

#Adaptive Gaussian Thresholding 
gray = cv2.medianBlur(gray,5) 
th3 = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2) 
cv2.imshow("images", th3) 
#cv2.ims 
cv2.waitKey(0) 

これは私が使用していた画像と、最終的なイメージである -

オリジナル画像:ガウスフィルタの後

enter image description here

enter image description here

+0

輪郭を探してみませんか?輪郭を見つけ、面積や周囲に基づいて小さいものを拒否し、大きいものを保持します。次に、残りの大きな輪郭の周囲に長方形を描き、座標を取得します。 –

答えて

0

あなたが作業している場合OpenCV 3.0、私はconnectedComponentsWithStatsの機能を見てお勧めします。

以下のスニペットは、イメージを開閉して消去し、輪郭を検出します。次に、輪郭と輪郭の中心を描画します。

# Create a kernel 
kernel = np.ones((7,7),np.uint8) 
# Use opening to fill the blobs 
opened = cv2.morphologyEx(th3, cv2.MORPH_OPEN, kernel) 
# Use closing to disconnect the bridges 
closed = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, kernel) 

# Create a color image to show the result 
new_img = cv2.cvtColor(closed, cv2.COLOR_GRAY2BGR) 
# Invert the image 
closed=255-closed 
# Find contours 
contours, hierarchy = cv2.findContours(closed, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) 

for cnt in contours: 
    # Skip if the contour area is small 
    area = cv2.contourArea(cnt) 
    if area < 500: 
     continue 
    # Draw the contour 
    cv2.drawContours(new_img, [cnt], -1, (0, 255, 0), 2) 
    # Find the center 
    M = cv2.moments(cnt) 
    cX = int(M["m10"]/M["m00"]) 
    cY = int(M["m01"]/M["m00"]) 
    # Draw the center 
    cv2.circle(new_img, (cX, cY), 7, (0, 0, 255), -1) 

cv2.imwrite("result.png",new_img) 

私は以下の結果を得たが、それはあなたが記述し、それはあまりにもあなたのために働く期待していたものだった願っています。

enter image description here

+0

次のエラーが発生しています - ValueError:輪郭を取得するためにアンパックする値が多すぎます –

+0

findContoursの実装はOpenCVのバージョンによって異なります。私はあなたのバージョンを知らないので、それはミスマッチでした。代わりに '_、contours、hierarchy = cv2.findContours(...)'を試してください。 – ilke444

+0

thnxそれは働いていました...私はopencv 3.0を持っていました...しかし、あなたはconnectedComponentsWithStatsがエリアにマークされているが、ラインにはないことを示唆しました。しかし、これは助けになりました。どうもありがとう。 –

関連する問題