MATLAB: How can i obtain inner region of the segmented regions, dynamically.

crop segmented regionsImage Processing Toolboxmarker control watershed

clear all
clc
[filename, pathname] = uigetfile({'*.*'},'Browse');
name=[pathname,filename];
rgb = imread(name);
I = rgb2gray(rgb);
hy = fspecial('laplacian',0.6);
hx = hy';
Iy = imfilter(double(I), hy, 'replicate');
Ix = imfilter(double(I), hx, 'replicate');
gradmag = sqrt(Ix.^2 + Iy.^2);
L = watershed(gradmag);
Lrgb = label2rgb(L);
se = strel('disk',5);
Io = imopen(I, se);
Ie = imerode(I, se);
Iobr = imreconstruct(Ie, I);
Ioc = imclose(Io, se);
Iobrd = imdilate(Iobr, se);
Iobrcbr = imreconstruct(imcomplement(Iobrd), imcomplement(Iobr));
Iobrcbr = imcomplement(Iobrcbr);
fgm = imregionalmax(Iobrcbr);
I2 = I; %superimpose
I2(fgm) = 255;
%clean the edges of the marker blobs
se2 = strel(ones(5,5));
fgm2 = imclose(fgm, se2);
fgm3 = imerode(fgm2, se2);
fgm4 = bwareaopen(fgm3,5);
I3 = I;
I3(fgm4) = 255;
%Compute Background Markers
bw = im2bw(Iobrcbr, graythresh(Iobrcbr));
D = bwdist(bw);
DL = watershed(D);
bgm = DL == 0;
%Compute the Watershed Transform of the Segmentation Function
gradmag2 = imimposemin(gradmag, bgm | fgm4);
L = watershed(gradmag2);
imtool(rgb);
s=size(rgb);
%Cropping image
imtool(L)
for i=1:max(max(L))
cimage=uint8(zeros(s(1,1),s(1,2),3));
cimage(:,:,1)=rgb(:,:,1).*uint8((L==i));
cimage(:,:,2)=rgb(:,:,2).*uint8((L==i));
cimage(:,:,3)=rgb(:,:,3).*uint8((L==i));
[u v]=find(L==i);
row=max(u)-min(u);
col=max(v)-min(v);
cimage=imcrop(cimage,[min(v) min(u) col row]);
%writing to specific folder
imshow(cimage);
name= input('enter name : ', 's');
imwrite(cimage,name,'jpg');
%pause
end
********** By running this above coding ,I can get segmented crop regions dataset. Such as ,
However , in my segmented crop regions contain dark region. I would like to crop inner region of the segmented regions dynamically by running coding and i don't want to obtain outer black regions. How can i modify this code ,Please help me.

Best Answer

Get a grayscale version using rgb2gray(). Then threshold the dark stuff:
grayImage = rgb2gray(rgbImage);
mask = grayImage < 90; % or whatever value you want.
Then zero out the dark things from the original image:
% Mask the image using bsxfun() function
maskedRgbImage = bsxfun(@times, rgbImage, cast(mask, class(rgbImage)));