2017-01-03 105 views
1

需要從圖像中檢測紅色並根據屏幕大小獲取座標。在python中使用opencv進行Blob過濾

  • 使用掩模取出圖像具有紅色
  • 轉換的部分它到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版本而異。由於我不知道你的版本,所以它是不匹配的。改爲使用'_,輪廓,層次結構= cv2.findContours(...)'。 – ilke444

+0

thnx它的工作...我有opencv 3.0 ...但正如你建議connectedComponentsWithStats標記區域,但不在線上。但是這有所幫助。非常感謝。 –