简体   繁体   English

如何使用 OpenCv + Python 找到 blob 的轮廓

[英]How to find the contour of a blob using OpenCv + Python

Goal目标

I want to use OpenCV in Python to find the precise contour of the blob , but ignore all the tentacles in the picture below:我想在 Python 中使用OpenCV找到blob的精确轮廓,但忽略下图中的所有触手

有触须的斑点

I need to find the precise contour so using dilate/erode is not ideal.我需要找到精确的轮廓,因此使用扩张/侵蚀并不理想。

You can use cv2.morphologyEx() with the morph open operation ( cv2.MORPH_OPEN ) and an elliptical shaped kernel ( cv2.MORPH_ELLIPSE ) created with cv2.getStructuringElement() .您可以将cv2.morphologyEx()与变形打开操作 ( cv2.MORPH_OPEN ) 和使用cv2.getStructuringElement()创建的椭圆形内核 ( cv2.MORPH_ELLIPSE ) 一起使用。 This is essentially an erosion followed by a dilation so this operation will remove the noise and keep the spherical shape of the blob.这本质上是先腐蚀后膨胀,因此此操作将消除噪声并保持 blob 的球形。 You can experiment with various kernel sizes to remove more or less of the blob and the strength of the operation by changing the number of iterations.您可以尝试使用各种内核大小,通过更改迭代次数来移除或多或少的 blob 和操作强度。 Here's the result after performing a morph open:这是执行变形打开后的结果:

在此处输入图片说明

From here we find the bounding box coordinates and draw a rectangle around the blob.从这里我们找到边界框坐标并在 blob 周围绘制一个矩形。

在此处输入图片说明

import cv2

image = 255 - cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
opening = cv2.morphologyEx(gray, cv2.MORPH_OPEN, kernel, iterations=4)

x,y,w,h = cv2.boundingRect(opening)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)

cv2.imshow('opening', opening)
cv2.imshow('image', image)
cv2.waitKey()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM