MATLAB: How to Segment this image efficiently

color segmentationimage analysisimage processingImage Processing Toolboximage segmentationleaf

I am pretty sure that we do not know what your specifications are. For example it gets a bit confusing about which parts of the stem on the right are parts of the foreground leaf and which are parts of a different leaf and we do not know what you want to do about that. Ah, the straight portion near the lower right edge is a bit of a torn part of the leaf so the leaf continues right down to the tube. But is that part of your specifications… we surely do not know.

Best Answer

Daniel, try this code:
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 = 20;
% Read in image.
rgbImage=imread('8.jpg');
subplot(2,2,1);
imshow(rgbImage);
title('Original RGB Image', 'FontSize', fontSize, 'Interpreter', 'None');
% Threshold
% Convert RGB image to chosen color space
hsvImage = rgb2hsv(rgbImage);
% Define thresholds for Hue based on histogram settings
hueMin = 0.139;
hueMax = 0.356;
% Define thresholds for Saturation based on histogram settings
saturationMin = 0.451;
saturationMax = 1.000;
% Create mask based on chosen histogram thresholds
mask = (hsvImage(:,:,1) >= hueMin ) & (hsvImage(:,:,1) <= hueMax) & ...
(hsvImage(:,:,2) >= saturationMin ) & (hsvImage(:,:,2) <= saturationMax);
% Fill holes.
mask=imfill(mask,'holes');
% Extract biggest blob.
mask = bwareafilt(mask, 1);
subplot(2,2,2);
imshow(mask)
title('Mask Image', 'FontSize', fontSize, 'Interpreter', 'None');
% Mask the image using bsxfun() function
maskedRgbImage = bsxfun(@times, rgbImage, cast(mask, 'like', rgbImage));
% Display final masked image
subplot(2,2,3);
imshow(maskedRgbImage)
title('Masked RGB Image', 'FontSize', fontSize, 'Interpreter', 'None');
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% 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')