John
John

Reputation: 1828

OpenCV detect the number pills in a tube

I have a transparent plastic tube that shall contain exactly 10 black little balls. But sometimes there will be 11 or 9 pills in there. Is there any way to detect the number of balls in the tube.

enter image description here

Now with cv2, the best I can do is the following:

import cv2
import numpy as np

original = cv2.imread("d.jpg", cv2.IMREAD_GRAYSCALE)
retval, image = cv2.threshold(original, 50, 255, cv2.THRESH_BINARY)

cv2.imshow('image',image)
cv2.waitKey(0)
cv2.destroyAllWindows()

I get a black and white image for a better contrast.

enter image description here

I tried to count the number of black pixels then divide it by a number to get the number of balls. But since there are many balls overlapping each other, it doesn't work well no matter how I tune that number.

Is there any other way to count them.

Here are more examples:

enter image description here enter image description here enter image description here

Upvotes: 1

Views: 1655

Answers (1)

Ozcan
Ozcan

Reputation: 726

You might want to try black-white image --> distance transform --> blur --> watershed transform. Here is the result I got in MATLAB

enter image description here

im=imread('tube.png');

% Transform
im=rgb2gray(im);

% Threshold
im=im>80;
im=imclose(im,strel('disk',2));
im=bwareaopen(im,10);

figure,
subplot(121);
imshow(im,[]);axis image;colormap gray

% Distance transform
imb=bwdist(im);

% Blur
sigma=4;
kernel = fspecial('gaussian',4*sigma+1,sigma);
im2=imfilter(imb,kernel,'symmetric');

% Watershed transform
L = watershed(max(im2(:))-im2);

% Plot
lblImg = bwlabel(L&~im);

subplot(122);
imshow(label2rgb(lblImg,'jet','k','shuffle'));

Upvotes: 8

Related Questions