在python中使用opencv进行Blob过滤

时间:2017-01-03 10:29:03

标签: 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

1 个答案:

答案 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