MATLAB: Calculate the width and height of the rectangle in this image automatically

circlegraphicsImage Processing Toolboxrectangleviscircles

How can I calculate the width and height of the rectangle in this image automatically? to use them in the next step

Best Answer

Seems to work for me:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clearvars;
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
folder = pwd;
baseFileName = 'image.png';
fullFileName = fullfile(folder, baseFileName);
rgbImage = imread(fullFileName);
% Display the original image.

subplot(2, 2, 1);
imshow(rgbImage, []);
axis('on', 'image');
caption = sprintf('Original Color Image\n"%s"', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.

% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0.05 1 0.95]);
% 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 Image Analyst', 'NumberTitle', 'Off')
% Extract the individual red, green, and blue color channels.
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
% Get the yellow mask.
yellowMask = redChannel == 255 & greenChannel == 255 & blueChannel == 0;
subplot(2, 2, 2);
imshow(yellowMask);
grid on;
title('Yellow Mask', 'FontSize', fontSize, 'Interpreter', 'None');
yellowMask = imfill(yellowMask, 'holes');
yellowMask = bwareafilt(yellowMask, 1);
subplot(2, 2, 3);
imshow(yellowMask);
grid on;
title('Yellow Mask, Filled', 'FontSize', fontSize, 'Interpreter', 'None');
% Find the Centroid, Equivalent Circular Diameter, and Bounding Box.
props = regionprops(yellowMask, 'Centroid', 'EquivDiameter', 'BoundingBox');
fprintf('Yellow Box Width = %d.\nYellow Box Height = %d.\n', props.BoundingBox(3), props.BoundingBox(4));
viscircles(props.Centroid, props.EquivDiameter/2);
% Display the original image.
subplot(2, 2, 4);
imshow(rgbImage, []);
axis('on', 'image');
caption = sprintf('With red circle centered over yellow square');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
viscircles(props.Centroid, props.EquivDiameter/2);