% Copyright 2005-2006 The MathWorks, Inc.
% This script requires a MATLAB Central submission called "Threhsolding
% Tool" by Robert Bemis (Submission ID #6770) for function "thresh_tool"
clear all; close all;
%% Access image acquisition device
vidobj = videoinput('winvideo');
start(vidobj);
%% Preview image to position camera
preview(vidobj);
%% Capture the image
rgb = getsnapshot(vidobj);
figure, imshow(rgb);
%% Segment all objects
I = rgb2gray(rgb);
background = imclose(I,strel('disk',15));
I2 = imsubtract(background,I);
BW = im2bw(I2,graythresh(I2));
BW = bwareaopen(BW, 20);
fill = imfill(BW,'holes');
figure, imshow(fill);
%% Post process results if necessary
level = thresh_tool(I2);
BW = im2bw(I2,level/255);
BW = bwareaopen(BW, 20);
fill = imfill(BW,'holes');
figure, imshow(fill);
%% Use feature analysis to identify broken objects
[statsDefects,stats] = getStatsOnDefects(BW);
%% Label broken objects
figure; imshow(rgb);
hold on;
for idx = 1 : length(statsDefects)
h = rectangle('Position', statsDefects(idx).BoundingBox, ...
'LineWidth', 2);
set(h,'EdgeColor',[.75 0 0]);
hold on;
end
hold off;
%% Clean up
delete(vidobj);
clear vidobj;
clear all; close all;