-
Notifications
You must be signed in to change notification settings - Fork 0
/
testimagesegmentation.m
112 lines (79 loc) · 2.5 KB
/
testimagesegmentation.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
function testimagesegmentation(imagefilepath)
%K means clustering
%READ A RGB IMAGE
A = imread(imagefilepath);
figure,subplot(121),imagesc(A);title('RGB Image');hold on;
A = double(A);
%CARTESIAN GRID FOR THE 2D IMAGE
[Xp,Yp] = meshgrid(1:size(A,2),1:size(A,1));
%NUMBER OF CLUSTERS
num_clusters = 4;
%THRESHOLD VALUE FOR EACH CHANNEL
Tval = 1;
%GLOBAL THRESHOLD VALUE
Global_Tval = 3;
%RANDOM IMAGE POSITIONS
RX = randi(size(A,1),1,num_clusters);
RY = randi(size(A,2),1,num_clusters);
%PREALLOCATE THE VECTORS
RGB_val = zeros([num_clusters,3]);
RGB_new = zeros([num_clusters,3]);
%FETCH THE RGB PIXEL VALUE OF THE RANDOM IMAGE POSITIONS
for j = 1:num_clusters
RGB_val(j,:) = A(RX(j),RY(j),:);
end
myvox = zeros([size(A,1) size(A,2) num_clusters]);
flag = 1;
Rcomp = A(:,:,1); %RED CHANNEL
Gcomp = A(:,:,2); %GREEN CHANNEL
Bcomp = A(:,:,3); %BLUE CHANNEL
it=0;
while flag==1
%EUCLIDEAN DISTANCE BETWEEN THE RANDOM RGB PIXEL VALUE
%AND THE PIXEL VALUES IN THE IMAGE
for j = 1: num_clusters
myvox(:,:,j) = sqrt((A(:,:,1)-RGB_val(j,1)).^2+(A(:,:,2)-RGB_val(j,2)).^2+(A(:,:,3)-RGB_val(j,3)).^2);
end
%FIND THE MINIMUM VALUE(Y) AND THE CORRESPONDING CLUSTER NUMBERS(ClusterMap)
[Y,ClusterMap] = min(myvox,[],3);
%MEAN VALUE PIXEL VALUES IN EACH CHANNEL WITH RESPECT TO THE CLUSTERS
for j = 1:num_clusters
RGB_new(j,1) = mean(Rcomp(ClusterMap(:)==j));
RGB_new(j,2) = mean(Gcomp(ClusterMap(:)==j));
RGB_new(j,3) = mean(Bcomp(ClusterMap(:)==j));
end
%DIFFERENCE BETWEEN THE NEW VALUE AND THE OLD VALUE
DiffVal = abs(RGB_val-RGB_new);
%IF THE DIFFERENCE IS LESS,STOP THE ITERATION ELSE
%ASSIGN THE NEW VALUE AND CONTINUE
if(sum(DiffVal(:)) < Global_Tval)
flag = 0;
else
if(sum(DiffVal(:,1))>Tval)
RGB_val(:,1) = RGB_new(:,1);
end
if(sum(DiffVal(:,2))>Tval)
RGB_val(:,2) = RGB_new(:,2);
end
if(sum(DiffVal(:,3))>Tval)
RGB_val(:,3) = RGB_new(:,3);
end
end
%NUMBER OF ITERATIONS
it=it+1;
end;
A = imread(imagefilepath);
[BW,maskedRGBImage] = createMask(A);
BW_groundTruth = rgb2gray(A);
a = sum(BW (:));
b = sum(BW_groundTruth (:));
Dice = (2*a)/b;
similarity = Dice;
subplot(122),imagesc(ClusterMap);title(['Clusters,Dice Index = ' num2str(similarity)]);colormap(jet);
%DISPLAY THE SEGMENTED IMAGE BASED ON COLORS
m=2;
n = round(num_clusters/m);
for k=1:num_clusters
F = repmat(logical(ClusterMap==k),1,1,3).*double(A);
figure(2),subplot(n,m,k),imagesc(uint8(F));hold on;
end