在Python中使用OpenCV进行Blob过滤 [英] Blob filtering using opencv in python

查看:308
本文介绍了在Python中使用OpenCV进行Blob过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要从图像中检测红色并获取基于屏幕尺寸的坐标.

Needed to detect red color from an image and get the coordinates based on screen size.

  • 使用蒙版获取红色图像的一部分
  • 已将其转换为BW
  • 对其应用了高斯滤波器.

最终图像中的小物体需要移除并获取其余物体的坐标.我尝试了SimpleBlobDetector,但没有帮助.这是我的代码-

The final image has small bodies which I need to remove and fetch the coordinates of the rest. I tried SimpleBlobDetector, but did not help. This is my code -

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)

这是我正在使用的图像,也是最终图像-

This is the image I am using and the final image -

原始图片:

在高斯滤波器之后

推荐答案

如果您正在使用OpenCV 3.0,建议您使用connectedComponentsWithStats函数.

If you are working on OpenCV 3.0, I would suggest you to look at connectedComponentsWithStatsfunction.

否则,下面的代码段将通过打开和关闭来清洁图像,然后找到轮廓.然后绘制轮廓和轮廓中心.

Else, the below snippet cleans the image with opening and closing, then finds the contours. Then it draws the contours and contour centers.

# 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)

我得到了以下结果,希望它就是您所描述的,并希望它也对您有用.

I got the following result, hope it was what you were describing, and hope it works for you too.

这篇关于在Python中使用OpenCV进行Blob过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆