How can I sepearte extruded part from its boundary in a grey scale image using matlab ?
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
Split the red and green portion in modified_image. Matlab code and images are attached.
채택된 답변
The simplest way is to just have the user encircle either the protrusions of the main trunk using drawpoly().
댓글 수: 4
But I have 100 images and the protrusion portion placed in different position in every images. So i could not seperate the main trunk and protrusions portion for all images.
Why not? If you hand trace, what's preventing you? Do you not know how to loop over files? If not, see
If it's a super complicated structure - so complicated that you don't know for sure what's a protrusion and what's not -- then developing an automated algorithm for those complicated images would be very difficult.
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.
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!');

추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Image Preview and Device Configuration에 대해 자세히 알아보기
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
