How to find maximum and minimum coordinates of a binary Image?

I have a color image, I converted it to black and white and removed noises. Now I want to find the Xmax, Ymax, Xmin, Ymin (maximum and minimum coordinates)of the white object in my Image so that I can draw a rectangle border around the Object. How can I achieve this. Please guide me!
Here is my image.

 Accepted Answer

This will do that for you:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
imtool close all; % Close all imtool figures if you have the Image Processing Toolbox.
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
% Read in demo image.
folder = 'C:\Users\Junaid\Documents';
baseFileName = '1.jpg';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% File doesn't exist -- didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
rgbImage = imread(fullFileName);
% Get the dimensions of the image.
% numberOfColorBands should be = 1.
[rows columns numberOfColorBands] = size(rgbImage);
% Display the original gray scale image.
subplot(2, 2, 1);
imshow(rgbImage, []);
title('Original Grayscale Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Give a name to the title bar.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
% Binarize the image by thresholding the green channel
binaryImage =rgbImage(:,:,2) > 128;
% Get rid of border.
binaryImage = imclearborder(binaryImage);
subplot(2, 2, 2);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize);
% Find limits;
vertical = any(binaryImage, 2);
horizontal = any(binaryImage, 1);
row1 = find(vertical, 1, 'first') % Y1
row2 = find(vertical, 1, 'last') % Y2
column1 = find(horizontal, 1, 'first') % X1
column2 = find(horizontal, 1, 'last') % X2
boxY = [row1 row1 row2 row2 row1];
boxX = [column1 column2 column2 column1 column1];
hold on;
plot(boxX, boxY, 'r-');

More Answers (1)

bb = regionprops(YourImage, 'BoundingBox');
rectangle( 'Position', bb.Boundingbox );

Categories

Find more on Display Image in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!