pythonopencvimage-processingconnected-components

Image processing with blob detection on binary image


My blob detector is not coloring my binary image. Can somone explain the problem?

code:

## mask of yellow color
mask_yellow = cv2.inRange(Img, (0, 180, 240), (20, 255, 255))

#define kernel size
kernel = np.ones((15,15), np.uint8)
# Remove unnecessary noise from mask
mask_yellow = cv2.morphologyEx(mask_yellow, cv2.MORPH_CLOSE, kernel)
mask_yellow = cv2.morphologyEx(mask_yellow, cv2.MORPH_OPEN, kernel)

#scale window size
mask_yellow_view = cv2.resize(mask_yellow, dsize)

#show yellow colors
cv2.imshow('Yellow mask', mask_yellow_view)

mask_yellow = cv2.bitwise_not(mask_yellow)

mask_yellow = cv2.cvtColor(mask_yellow, cv2.COLOR_GRAY2RGB)

params = cv2.SimpleBlobDetector_Params()

params.filterByArea = True
params.minArea = 10000

detector = cv2.SimpleBlobDetector_create(params)
keypoints = detector.detect(mask_yellow)

blank = np.zeros((20, 20))
blobs = cv2.drawKeypoints(mask_yellow, keypoints, blank, (0, 0, 255),cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)


# Show keypoints
cv2.imshow("Keypoints", blobs)

Solution

  • For me your code works fine. Here is the simplified code I used and my sample input and output image. The params.minArea threshold was too high in my case, so I had to lower it. Please check if your filter criteria fits to your input!

    import cv2
    
    img = cv2.imread("img.png")
    
    # mask of yellow color
    mask_yellow = cv2.inRange(img, (0, 180, 240), (20, 255, 255))
    mask_yellow = cv2.bitwise_not(mask_yellow)
    mask_yellow = cv2.cvtColor(mask_yellow, cv2.COLOR_GRAY2RGB)
    
    params = cv2.SimpleBlobDetector_Params()
    
    params.filterByArea = True
    params.minArea = 1000
    
    detector = cv2.SimpleBlobDetector_create(params)
    keypoints = detector.detect(mask_yellow)
    
    blobs = cv2.drawKeypoints(mask_yellow, keypoints, 0, (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
    
    cv2.imwrite("out.png", blobs)
    

    Input image:

    Input image

    Output image:

    enter image description here