How can I sepearte extruded part from its boundary in a grey scale image using matlab ?

2 visualizzazioni (ultimi 30 giorni)
Split the red and green portion in modified_image. Matlab code and images are attached.

Risposta accettata

Image Analyst
Image Analyst il 25 Set 2022
The simplest way is to just have the user encircle either the protrusions of the main trunk using drawpoly().
  4 Commenti
Surendra Ratnu
Surendra Ratnu il 28 Set 2022
Agreed with your point. But The protrusion part have a different location in every image and it is random. we could not predict what is location of the protrusion in every images.
Image Analyst
Image Analyst il 28 Set 2022
I don't know why that would prevent people from being able to see where to chop off the protrusions. However if you insist on an automatic way, here is a start. There are other ways though to smooth out the left edge, like fit it with a Savitzky-Golay filter.
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;
% Have user browse for a file, from a specified "starting folder."
% For convenience in browsing, set a starting folder from which to browse.
startingFolder = pwd; % or 'C:\wherever';
if ~exist(startingFolder, 'dir')
% If that folder doesn't exist, just start in the current folder.
startingFolder = pwd;
end
% Get the name of the file that the user wants to use.
defaultFileName = fullfile(startingFolder, 'protrusions.png');
[baseFileName, folder] = uigetfile(defaultFileName, 'Select a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
%===============================================================================
% Check if file exists.
if ~isfile(fullFileName)
% 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);
uiwait(warndlg(errorMessage));
return;
end
end
rgbImage = 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(rgbImage)
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(rgbImage);
% 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 = rgbImage(:, :, 1); % Take red channel.
else
grayImage = rgbImage; % It's already gray scale.
end
% Now it's gray scale with range of 0 to 255.
% Display the image.
subplot(3, 2, 1);
imshow(grayImage, []);
title('Original Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
hp = impixelinfo();
%------------------------------------------------------------------------------
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);
% 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;
% Display the image.
subplot(3, 2, 2);
histogram(grayImage);
grid on;
title('Histogram of Gray Scale Image', 'FontSize', fontSize, 'Interpreter', 'None');
% Use fixed thresholds.
lowThreshold = 0;
highThreshold = 180;
% % Use triangle threshold method on the image
% pixelCounts = imhist(grayImage, 256);
% % pixelCounts(1:2) = 0; % Suppress gray level of background since those bins would be so high.
% showPlot = true;
% highThreshold = triangle_threshold(pixelCounts, 'L', showPlot)
% Interactively and visually set a threshold on a gray scale image.
% https://www.mathworks.com/matlabcentral/fileexchange/29372-thresholding-an-image?s_tid=srchtitle
% [lowThreshold, highThreshold, lastThresholdedBand] = threshold(lowThreshold, highThreshold, grayImage);
% Show line on histogram.
hold on;
xline(highThreshold, 'Color', 'r', 'LineWidth', 2);
% Binarize the image.
mask = grayImage > lowThreshold & grayImage < highThreshold;
% Take largest blob.
mask = bwareafilt(mask, 1);
% Display the mask.
subplot(3, 2, 3);
imshow(mask, []);
title('Mask', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
% For each line, take only the longest stretch of white.
for row = 1 : rows
thisRow = mask(row, :);
% Find the rightmost blob.
props = regionprops(thisRow, 'Centroid');
xy = vertcat(props.Centroid);
% Find the max x value
[maxx, indexOfRightBlob] = max(xy(:, 1));
if indexOfRightBlob > 1
% Extract the right blob only.
labeledImage = bwlabel(thisRow);
thisRow = ismember(labeledImage, indexOfRightBlob);
% Put back into the mask
mask(row, :) = thisRow;
end
end
% Display the mask.
subplot(3, 2, 4);
imshow(mask, []);
title('Cleaned Mask', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
% Find the left and right sides.
leftCol = nan(1, columns);
rightCol = nan(1, columns);
for row = 1 : rows
t = find(mask(row, :), 1, 'first');
if ~isempty(t)
leftCol(row) = t;
rightCol(row) = find(mask(row, :), 1, 'last');
end
end
% Plot right edge in red:
y = 1 : rows;
hold on;
plot(rightCol, y, 'r-', 'LineWidth', 2);
% Plot left edge in yellow:
plot(leftCol, y, 'y-', 'LineWidth', 2);
% Get the widths
widths = rightCol - leftCol;
% Get the average width
meanWidth = mean(widths)
% Scan down and if any width is more than 1.5 * the mean width, crop it.
factor = 1.3;
for row = 1 : rows
thisWidth = widths(row);
if isnan(thisWidth)
continue;
end
if thisWidth > factor * meanWidth
% Find the column we need to zero out to
col = round(rightCol(row) - factor * meanWidth)
% Zero out on the left up until there.
mask(row, 1:col) = false;
end
end
% Display the mask.
subplot(3, 2, 5);
imshow(mask, []);
title('Cleaned Mask', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
msgbox('Done!');

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Image Processing Toolbox in Help Center e File Exchange

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by