How to detect the dimension of a square section in an image ?

1 view (last 30 days)
I have an image where I want to get the dimensions of the square sections. There are 3 squares in the image you can find. I have uploaded the image.
I don't have any idea how to start.
Atik Amin
Atik Amin on 31 May 2023
It's the extraction of an image after ultrasonic testing. I have data but at those certain point which data to pick is uncertain as the data contains 401 x 401 samples

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 31 May 2023
Try this:
% Demo by Image Analyst
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 = 18;
markerSize = 40;
folder = pwd;
baseFileName = 'ultrasound.png';
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
grayImage = imread(fullFileName);
% Display the image.
subplot(2, 2, 1);
imshow(grayImage, []);
axis('on', 'image');
title('Original Image', 'FontSize', fontSize, 'Interpreter', 'None');
% 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.
fprintf('It is not really gray scale like we expected - it is color\n');
% Extract the max channel.
% grayImage = max(grayImage, [], 3);
% Extract the green channel.
grayImage = grayImage(:, :, 2);
% Maximize window.
g = gcf;
g.WindowState = 'maximized';
g.NumberTitle = 'off';
g.Name = 'Demo by Image Analyst'
% Threshold to create mask of the dark spot.
lowThreshold = 0;
highThreshold = 94;
% Interactively and visually set a threshold on a gray scale image.
% [lowThreshold, highThreshold] = threshold(lowThreshold, highThreshold, grayImage)
mask = grayImage >= lowThreshold & grayImage <= highThreshold;
% Check the areas of the initial mask
props = regionprops(mask, 'Area');
allAreas = sort([props.Area])
% Take blobs only if they're larger than 20000 pixels.
mask = bwareafilt(mask, [20000, inf]);
subplot(2, 2, 2);
axis('on', 'image');
title('Mask Image', 'FontSize', fontSize, 'Interpreter', 'None');
% Get the areas and center of the final square blobs.
props = regionprops(mask, grayImage, 'Area', 'Centroid', 'MeanIntensity');
allAreas = sort([props.Area]);
meanBlobGrayLevels = [props.MeanIntensity];
subplot(2, 2, 3);
axis('on', 'image');
title('Mask Image', 'FontSize', fontSize, 'Interpreter', 'None');
% Let's assume they are square. Get the width of the square.
squareWidth = sqrt(allAreas);
% Plot squares over image
subplot(2, 2, 4);
axis('on', 'image');
title('Mask Image', 'FontSize', fontSize, 'Interpreter', 'None');
caption = sprintf('Mean of region = %.1f gray levels.', meanBlobGrayLevels)
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hold on;
for k = 1 : length(props)
% Get rectangle in form [xLeft, yTop, width, height];
r = [props(k).Centroid(1) - squareWidth(k)/2, props(k).Centroid(2) - squareWidth(k)/2, squareWidth(k), squareWidth(k)]
rectangle('Position', r, 'EdgeColor', 'y', 'LineWidth', 2);
hold off;
% Get boundary of region and plot it over original image.
% Plot the borders of all the blobs in the overlay above the original grayscale image
% using the coordinates returned by bwboundaries().
% bwboundaries() returns a cell array, where each cell contains the row/column coordinates for an object in the image.
% Here is where we actually get the boundaries for each blob.
boundaries = bwboundaries(mask);
% boundaries is a cell array - one cell for each blob.
% In each cell is an N-by-2 list of coordinates in a (row, column) format. Note: NOT (x,y).
% Column 1 is rows, or y. Column 2 is columns, or x.
numberOfBoundaries = size(boundaries, 1); % Count the boundaries so we can use it in our for loop
% Here is where we actually plot the boundaries of each blob in the overlay.
hold on; % Don't let boundaries blow away the displayed image.
for k = 1 : numberOfBoundaries
thisBoundary = boundaries{k}; % Get boundary for this specific blob.
x = thisBoundary(:,2); % Column 2 is the columns, which is x.
y = thisBoundary(:,1); % Column 1 is the rows, which is y.
plot(x, y, 'r-', 'LineWidth', 2); % Plot boundary in red.
hold off;
caption = sprintf('Mean Area = %.1f pixels with a threshold of %d.', mean(allAreas), highThreshold);
fontSize = 15;
title(caption, 'FontSize', fontSize);
axis('on', 'image'); % Make sure image is not artificially stretched because of screen's aspect ratio.
Do it similarly for the bright squarish region.

More Answers (1)

Image Analyst
Image Analyst on 31 May 2023
Edited: Image Analyst on 31 May 2023
Simply threshold the underlying grayscale image (not the pseudocolored image) and call bwareafilt to extract the 3 largest blobs. Then you can compute the area, mean intensity, bounding box, or whatever you want.
In short:
mask = bwareafilt(grayImage > someThreshold, 3);
props = regionprops('table', mask, grayImage, 'Area', 'BoundingBox', 'MeanIntensity')
For a full demo, see my Image Segmentation Tutorial in my File Exchange:
It's a generic, general purpose demo of how to threshold an image to find blobs, and then measure things about the blobs, and extract certain blobs based on their areas or diameters.
Also see
for an interactive function to find the appropriate threshold, since it is a judgment call.
DGM on 31 May 2023
inpict = imread('notdata.png');
% crop the plot area from the screenshot
hsvpict = rgb2hsv(inpict);
mask = hsvpict(:,:,2)>0.5;
mask = bwareafilt(mask,1);
S = regionprops(mask,'boundingbox');
inpict = imcrop(inpict,S.BoundingBox);
% try to inpaint to get rid of the annotation
mask = all(inpict >= 0.9*255,3);
mask = imdilate(mask,ones(3));
for c = 1:size(inpict,3)
inpict(:,:,c) = regionfill(inpict(:,:,c),mask);
% guess what the colormap is and estimate the data
% we have no idea what scale it's on, so just put it in unit-scale
CT = jet(256);
estdata = im2double(rgb2ind(inpict,CT));
% now we have something that's similar to the data
%ROI = drawrectangle(gca)
... but if you have the data, there's no good reason to estimate it from a screenshot. Just use the actual undamaged data.

Sign in to comment.


Find more on Image Processing Toolbox 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!