Mohamed Ragih
Mohamed Ragih

Reputation: 1

detecting countours of this image using opencv

I want to detect white blood cells (WBCs) and count them, so i had to make some steps and reached this image and don't know what to do next.

Original image:

Original image

gray then closing morphology then thresholding:

gray then closing morphology then thresholding

my code

import cv2
import numpy as np

# Read image
im = cv2.imread("images/image.jpg")
output = im.copy()
hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
gray_image = cv2.cvtColor(hsv, cv2.COLOR_BGR2GRAY)
blurG = cv2.GaussianBlur(gray_image, (9, 9), 0)
blurM = cv2.medianBlur(gray_image, 5)
cv2.imwrite("gray.jpg",gray_image)


res,thresh_img=cv2.threshold(blurM,135,255,cv2.THRESH_BINARY_INV)
kernel = np.ones((5,5),np.uint8) 
closing= cv2.morphologyEx(thresh_img,cv2.MORPH_CLOSE,kernel,iterations=2)
cv2.imwrite("result3.jpg",closing)

Upvotes: 0

Views: 322

Answers (1)

Colim
Colim

Reputation: 1303

If the point is on a contour, it has neighbors with different values, and the gaussian blur with neigbors will be different.

So you just check for differences between "closing" image and his gaussian blur.

blurNeighbor = cv2.GaussianBlur(closing, (3, 3), 0)

#contour is any "closing" pixel different from "blurNeighbor"
contour=(blurNeighbor!=closing).astype(np.uint8)*255
cv2.imshow("Contour", contour)
cv2.waitKey(10)

contour

You can estimate the number of blobs by dividing the number of black pixels in "closing" by the median blob size.

For this image, it gives 33.5 blobs:

#detect blobs in "closing"
params = cv2.SimpleBlobDetector_Params()
params.filterByArea = False
params.filterByInertia = False
params.filterByConvexity = False

detector=cv2.SimpleBlobDetector_create(params)
blobs=detector.detect(closing)

#draw detected blobs
img_with_keypoints = cv2.drawKeypoints(closing, blobs, outImage=np.array([]), color=(0, 0, 255),flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
cv2.imshow("Detected blobs", img_with_keypoints)
cv2.waitKey(10)

#estimate the number of blobs
blobAreas=np.sort([np.pi/4*b.size**2 for b in blobs])
medianArea=np.median(blobAreas)
blobCountEstimation=np.sum(closing==0)/medianArea

print(f"Estimated number of blobs: {blobCountEstimation:.1f}")
>>>Estimated number of blobs: 33.5

detected blobs

Upvotes: 2

Related Questions