Detecting small rectangles in a picture

2 views (last 30 days)
I want to get only the rectangles at the bottom, but the problem is that they are not all evenly divided by black. this is what I've got so far: http://i1016.photobucket.com/albums/af289/galga2010/Figure2_zps65020947.png
With this code:
clear
clc
close all
img = '4Test.png';
I = imread(img);
Ibw = rgb2gray(I);
imshow(Ibw);
Ifill = imfill(Ibw,'holes');
imshow(Ifill);
Iarea = bwareaopen(Ifill,100);
imshow(Iarea);
Ifinal = bwlabel(Iarea);
imshow(Ifinal);
stat = regionprops(Ifinal,'boundingbox');
imshow(I); hold on;
shpNum = 0;
green = 0;
red = 0;
for cnt = 1 : numel(stat)
bb = stat(cnt).BoundingBox;
if (bb(1,3)<800)
x = bb(1,1);
y = bb(1,2);
Color = impixel(I,x + 2,y + 2);
if Color == [28 131 4];
green = green +1;
elseif Color == [237 28 36]
red = red +1;
end
rectangle('position',bb,'edgecolor','b','linewidth',2);
shpNum = shpNum + 1;
end
end
formatSpec = 'There are %d rectangles \n';
fprintf(formatSpec,shpNum);
formatSpec = 'There are %d green rectanlges \n';
fprintf(formatSpec,green);
formatSpec = 'There are %d red rectangles \n';
fprintf(formatSpec,red);
Any Ideas?
Thank you

Accepted Answer

Image Analyst
Image Analyst on 24 Sep 2013
You can't convert to gray - that throws away all color info. You need to do color segmentation, something like (untested)
% Extract the individual red, green, and blue color channels.
redChannel = rgbImage(:, :, 1); % Call imshow(redChannel) if you want to see it.
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
threshold = 128; % or whatever.
redPixels = redChannel > threshold & greenChannel < threshold & blueChannel < threshold;
greenPixels = redChannel < threshold & greenChannel > threshold & blueChannel < threshold;
bluePixels = redChannel < threshold & greenChannel < threshold & blueChannel > threshold;
% Then call imfill to fill the holes
redPixels = imfill(redPixels, 'holes');
greenPixels = imfill(greenPixels, 'holes');
bluePixels = imfill(bluePixels, 'holes');
% Then call bwlabel to count the number of blobs:
[lr, countR] = bwlabel(redPixels);
[lg, countG] = bwlabel(greenPixels);
[lb, countB] = bwlabel(bluePixels);
% Call regionprops if you want bounding boxes.
measurementsR = regionprops(lr, 'BoundingBox');
measurementsG = regionprops(lg, 'BoundingBox');
measurementsB = regionprops(lb, 'BoundingBox');

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!