MATLB code for Image Segmentation


MATLB code for Image Segmentation



he= imread('G:\landsat vellore2010\b-feb2010.jpg');
imshow(he), title('ORIGINAL IMAGE');
text(size(he,2),size(he,1)+15,...
     'Vellore,Tamilnadu,India', ...
     'FontSize',7,'HorizontalAlignment','right');
 cform = makecform('srgb2lab');
lab_he = applycform(he,cform);
ab = double(lab_he(:,:,2:3));
nrows = size(ab,1);
ncols = size(ab,2);
disp(nrows);
disp(ncols);
ab = reshape(ab,nrows*ncols,2);
nColors = 6;
% repeat the clustering 3 times to avoid local minima
[cluster_idx cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean','replicates',3);
pixel_labels = reshape(cluster_idx,nrows,ncols);
%figure, imshow(pixel_labels,[]), title('image labeled by cluster index');
segmented_images = cell(1,3);
rgb_label = repmat(pixel_labels,[1 1 3]);

for k = 1:nColors
    color = he;
    color(rgb_label ~= k) = 0;
    segmented_images{k} = color;
end

figure, imshow(segmented_images{1}), title('objects in cluster 1');
figure, imshow(segmented_images{2}), title('objects in cluster 2');
figure, imshow(segmented_images{3}), title('objects in cluster 3');
figure, imshow(segmented_images{4}), title('objects in cluster 4');
figure, imshow(segmented_images{5}), title('objects in cluster 5');
figure, imshow(segmented_images{6}), title('objects in cluster 6');
i=imread('G:\landsat vellore2010\b-feb2010.jpg');
figure,imshow(i);
title('true color')
figure
imhist(i(:,:,3))
title('histogram')
r=i(:,:,1);
g=i(:,:,2);
b=i(:,:,3);
figure
plot3(r(:),g(:),b(:),'.')
grid('on')
xlabel('Red(Band3)')
ylabel('Green(Band2)')
zlabel('Blue(Band1)')
title('visible bands')
h=imadjust(i,stretchlim(i));
figure
imshow(h)
title('AFTER CONTRAST')
figure
imhist(h(:,:,3))
title('Histogram of Red Band (Band 3) after Contrast Stretch')
figure,imhist(h(:,:,2))
title('Histogram of green Band (Band 2) after Contrast Stretch')
figure,imhist(h(:,:,1))
title('Histogram of blue Band (Band 1) after Contrast Stretch')
j = decorrstretch(i, 'Tol', 0.01);
figure
imshow(j)
title('Truecolor Composite after Decorrelation Stretch')
r = j(:,:,3);
g = j(:,:,2);
b = j(:,:,1);
figure
plot3(r(:),g(:),b(:),'.')
grid('on')
xlabel('Red (Band 3)')
ylabel('Green (Band 2)')
zlabel('Blue (Band 1)')
title('Scatterplot of the Visible Bands after Decorrelation Stretch')
figure,imtool(j)
i=imread('G:\landsat vellore2010\b-feb2010.jpg');
imshow(i);
j=imcrop(i);
figure,imshow(j)
I=imread('G:\landsat vellore2010\b-feb2010.jpg');
imshow(I);
imtool(I);