MATLAB: How to tell the number of defective tablets using matlab

contourimage processingMATLAB

I'm working on a project, where I have to display the number of defected tablets. Till now I'm done with the preprocessing like:
1. rgb2gray
2. gray to binary image
3. bwmorph (erode and remove)
This is the tablet blister I'm working with:
This the resultant image after the pre-processing operations on the original image:
Here's a section of my code which tells the difference between the ideal blister and the defective one.
% Calculate the Normalized Histogram of Image 1 and Image 2
hn1 = imhist(Imageg1)./numel(Imageg1);
hn2 = imhist(Imageg2)./numel(Imageg2);
% Calculate the histogram error/ Difference
f1 = sum((hn1 - hn2).^2);
set(handles.text3,'String',f1)
if sum( abs( I1(:) - I2(:) ) ) == 0.0
h=msgbox(' No Defect Found');
else
h=msgbox(' Defect Found');
end
Is there any way I can tell how many tablets are defective?
Thanks in advance!

Best Answer

This kind of "missing part" image analysis is trivial in machine vision. The usual method, because it's the easiest, is to just have a template and look at the mean intensity inside the templates mask. The intensity is either what is should be, or, if part of the pill is missing, it will be less.
labeledImage = bwlabel(binaryImage);
measurements = regionprops(labeledImage, grayImage, 'MeanIntensity');
allIntensities = [measurements.MeanIntensity];
goodOnes = allIntensities > someThreshold;