MATLAB: Identifying number on dice

cropimage processing

% I want to crop the front face of dice and identify the number on it. I tried the following
A=imread('dice.png');
figure,imshow(A); title('Original Image');
%Convert the Image to binary
B=im2bw(A);
%Fill the holes
C=imfill(B,'holes');
%Label the connected components
[Label,Total]=bwlabel(C,8);
figure,imshow(C); title('Labelled Image');
% then I did the following
D=imsubtract(B,C);
imshow(D);
%
where Background is black, dice is white with black dots. But WHEN BACKGROUND IS NOT PERFECTLY BLACK THEN IT CREATES PROBLEM. CAN YOU PLZ TELL ME HOW REMOVE BACKGROUND AND CROP ONLY DICE PART?

Best Answer

Hi Sameer, Here's what I would do. It's a little like IA's bwareaopen suggestion. It tries to make minimal assumptions other than:
  1. Dice are white and bigger than 1000 pixels
  2. (front facing) dots are surrounded by dice and bigger than 50 pixels
% Fetch the image
I = imread('http://www.mathworks.com/matlabcentral/answers/uploaded_files/13250/dice1.jpg');
G = rgb2gray(I);
% Dice are white and big
diceBlobs = bwareaopen(G>180, 1000);
cc = bwconncomp(diceBlobs);
diceLabels = labelmatrix(cc);
for i = 1:cc.NumObjects
thisDice = diceLabels==i;
% Dots are surrounded by dice and +50 pixels
thisDots = bwareaopen(imfill(thisDice,'holes') & ~thisDice, 50);
dotsCC = bwconncomp(thisDots);
figure, imshow(thisDice*0.5 + thisDots)
title(sprintf('Dice #%d has %d dots',i,dotsCC.NumObjects))
end
Does this code help you out? You could certainly add some further criteria such as dots needing to be round (I would use regionprops and look at, say, the Solidity property), and maybe dice should be square, but this seems reasonably robust as long as your pictures are all quite similar.
Thanks, Sven.