How to reduce blob using aspect ratio?

.
I have a binary image with 4 blobs. 3 of them has an aspect ratio of more than 1. and 1 has aspect ratio of 1. Now I want to reduce that blobs which aspect ratio more than 1 in binary image. How could i do this. Can some one please provide a code??
A picture is provided for understanding.

2 Comments

When you say "reduce" do you mean "set to black" ?

Sign in to comment.

 Accepted Answer

Dominic, here is the full demo:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 25;
%===============================================================================
% Get the name of the image the user wants to use.
baseFileName = '4.png';
% Get the full filename, with path prepended.
folder = []; % Determine where demo folder is (works with all versions).
fullFileName = fullfile(folder, baseFileName);
%===============================================================================
% Read in a demo image.
grayImage = imread(fullFileName);
% Get the dimensions of the image.
% numberOfColorChannels should be = 1 for a gray scale image, and 3 for an RGB color image.
[rows, columns, numberOfColorChannels] = size(grayImage)
if numberOfColorChannels > 1
% It's not really gray scale like we expected - it's color.
% Use weighted sum of ALL channels to create a gray scale image.
grayImage = rgb2gray(grayImage);
% ALTERNATE METHOD: Convert it to gray scale by taking only the green channel,
% which in a typical snapshot will be the least noisy channel.
% grayImage = grayImage(:, :, 2); % Take green channel.
end
% Display the image.
subplot(2, 1, 1);
imshow(grayImage, []);
axis on;
axis image;
caption = sprintf('Original Gray Scale Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo();
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
drawnow;
% Threshold the image.
binaryImage = grayImage > 128;
% Find connected components (blobs).
labeledImage = bwlabel(binaryImage);
% Make the measurements of the bounding boxes.
props = regionprops(labeledImage, 'BoundingBox');
bb = [props.BoundingBox];
allWidths = bb(3:4:end)
allHeights = bb(4:4:end)
aspectRatio = [allWidths./allHeights ; allHeights ./ allWidths]
aspectRatios = max(aspectRatio, [], 1)
compactIndexes = find(aspectRatios > 1.5) % or whatever.
% Extract only those blobs with high aspect ratios.
binaryImage = ismember(labeledImage, compactIndexes);
% Display the image.
subplot(2, 1, 2);
imshow(binaryImage, []);
axis on;
axis image;
caption = sprintf('Final binary image with only high aspect ratio blobs');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');

3 Comments

Thank you very much sir. I have finally figured out how to solve the problem in your final contribution. I just needed to change the condition.
And one more help please, can u please give me some effective reference on filtering by SOLIDITY . Or reducing connected component by SOLIDITY .
If you have a fairly recent version of MATLAB, you can filter by that before you even call bwconncomp(), bwlabel() or regionprops(). Just call bwpropfilt() and pass in the min and max values you want to accept.
Thank you sir for giving me your precious time. I have solved that problem too.

Sign in to comment.

More Answers (2)

If you used regionprops() to get the BoundingBox in order to calculate the aspect ratio, then you can also ask for the pixel ID list. For each region that does not pass your aspect ratio test, assign 0 to the pixels given by those indices.

9 Comments

I have used vision.BlobAnalysis. And here is my code. I have detected my result in boundingbox. Now i just want to make other blobs pixel to zero. And stuck at this point. I don't know how to get pixelLists of other blobs that do not satisfy the condition.
First one is input image.
binaryImg = imread('4.png');
binaryImg = im2bw(binaryImg);
blobAnalyzer = vision.BlobAnalysis;
% Run the blob analyzer to find connected components and their
statistics.
[area, centroids, roi] = step(blobAnalyzer, binaryImg);
binary_image = im2uint8(binaryImg);
%calculating aspect ratio
width = roi(:,3);
height = roi(:,4);
aspectRatio = width ./ height;
%checking condition if setisfied
roi = roi( aspectRatio == 1 ,:);
%than draw a rectangle
img = insertShape(binary_image, 'rectangle', roi, 'color', {'red'});
figure;
imshow(img);
Before discarding the roi entries with the aspect ratio you do not want, use those roi to zero parts of the array. Just remember that X corresponds to columns and Y corresponds to rows.
There could potentially be a problem if the roi overlap though.
Can u please provide a sample code.
unwanted_roi = roi( aspectRatio ~= 1 ,:);
for K = 1 : size(unwanted_roi,1)
this_roi = unwanted_roi(K,:);
binary_image(this_roi(2) : this_roi(2) + this_roi(4) - 1, this_roi(1) : this_roi(1) - 1) = 0;
end
Thank you very much.
But, it gives error in the first line that is matrix dimension exceeds.
unwanted_roi = roi( aspectRatio ~= 1 ,:);
Could you attach the original image? The one that does not have the red rectangles on it?
Change the line to
binary_image(this_roi(2) : this_roi(2) + this_roi(4) - 1, this_roi(1) : this_roi(1) + this_roi(3) - 1) = 0;
Still getting error from the line
unwanted_roi = roi( aspectRatio ~= 1 ,:);
"Index exceeds matrix dimensions"

Sign in to comment.

Use regionprops() to ask for the bounding box. Then compute aspect ratio: width over height, and height over width and take the max (or min), whichever you're using. Then use find() to find out which blobs to keep, then use ismember() to extract only those blobs. See my Image Segmentation Tutorial for a detailed demo. http://www.mathworks.com/matlabcentral/fileexchange/?term=authorid%3A31862&sort=downloads_desc

2 Comments

Thank you very much. i think i could find what i need, from your tutorial.
If I have more time later I'll help more, in the meantime, do this:
props = regionprops(labeledImage, 'BoundingBox');
bb = [props.BoundingBox];
allWidths = bb(3:4:end);
allHeights = bb(4:4:end);
aspectRatio = [allWidths./allHeights ; allHeights ./ allWidths]
aspectRatios = max(aspectRatio, [], 1)
compactIndexes = find(aspectRatios > 5); % or whatever.
binaryImage = ismember(labeledImage, compactIndexes);

Sign in to comment.

Asked:

on 18 Jul 2017

Commented:

on 19 Jul 2017

Community Treasure Hunt

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

Start Hunting!