MATLAB: Segmentation of rice grains and sub plotting individual grains

ricesegmentationsubplotting

in the code attached, i want all the segmented rice images to appear in the form of subplot but this code keeps me giving the output as the last rice image in subplot.Thanks in advance.(this code was developed with the help of some codes present on the internet)
a=imread('r-1121.jpeg');
figure,imshow(a);
title('original image');
I1 = rgb2gray(a);
I1=imsharpen(I1);
I=medfilt2(I1);
b=imbinarize(I);
figure,
imshow(b);
c=imfill(b,'holes');
label=bwlabel(c);
for j=1:max(max(label))
[row,col]=find(label==j);
len=max(row)-min(row)+2;
breadth=max(col)-min(col)+2;
target=uint8(zeros([len breadth] ));
sy=min(col)-1;
sx=min(row)-1;
for i=1:size(row,1)
x=row(i,1)-sx;
y=col(i,1)-sy;
target(x,y)=a(row(i,1),col(i,1));
end
for k=1:25
mytitle=strcat('Rice number: ',num2str(j));
ax=subplot(1,25,k);
imshow(target);
end
end

Best Answer

You don't need the inner plot loop, and some other stuff can be simplified. I just removed the figure and imshow previews for brevity.
a=imread('rice.jpg');
I1 = rgb2gray(a);
I1=imsharpen(I1);
I=medfilt2(I1);
b=imbinarize(I);
c=imfill(b,'holes');
label=bwlabel(c);
numgrains = max(label(:));
for j=1:numgrains
[row,col]=find(label==j);
len=max(row)-min(row)+2;
breadth=max(col)-min(col)+2;
xrange = min(col)-1+(0:breadth);
yrange = min(row)-1+(0:len);
target = a(yrange,xrange) .* uint8(c(yrange,xrange)); % NOTE

mytitle=strcat('Rice number: ',num2str(j)); % not used yet

ax=subplot(1,numgrains,j);
imshow(target);
end
Alternatively, you can get the location using regionprops():
a=imread('rice.jpg');
I1 = rgb2gray(a);
I1=imsharpen(I1);
I=medfilt2(I1);
b=imbinarize(I);
c=imfill(b,'holes');
S=regionprops(c,'boundingbox');
numgrains = numel(S);
for j=1:numgrains
tp = round(S(j).BoundingBox);
xrange = tp(1)+(-1:tp(3)+1);
yrange = tp(2)+(-1:tp(4)+1);
target = a(yrange,xrange) .* uint8(c(yrange,xrange)); % NOTE
mytitle=strcat('Rice number: ',num2str(j)); % not used yet
ax=subplot(1,numgrains,j);
imshow(target);
end
You might need to tweak the subscript vectors by a pixel to get your padding exactly as you want it.
In both examples, I made a note on the same line. In your original code, the pointwise method only extracts the portion of the image selected by the mask c. If on the other hand, you wanted to select the region of the image defined by the bounding box you calculate around the image, then change that line to
target = a(yrange,xrange);
The first method truncates the edges of the grains according to the mask and makes them jagged. The second method shows the grains with their local background and natural edges. Which to use depends what your intent is for using the images of the objects.