Skip to content Skip to sidebar Skip to footer

Blob Filtering Using Opencv In Python

Needed to detect red color from an image and get the coordinates based on screen size. Using mask fetched the part of image having red color Converted it to BW Applied Gaussian

Solution 1:

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.

enter image description here

Post a Comment for "Blob Filtering Using Opencv In Python"