Monday, June 10, 2024

ML: The code of K-Nearest Neighbors

  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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
% Created by LI Xu
% Version 1.0
% May 31, 2024

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/


clear;
clc;

timebegin=tic;
cur_data=date;
cur_time=fix(clock);
str1=sprintf('%s %.2d:%.2d:%.2d', cur_data, cur_time(4), cur_time(5), cur_time(6)); 
fprintf('Time Begin: ');
fprintf(str1);
fprintf('\n');


% settings********************************************
% BackValue
BackVal=0;
fieldname='id';
cropname='canola';
% ***************************************************

% Source Directory
SouDir='input';
% Destination Directory
DesDir='output';

% All images
files=dir(fullfile(SouDir, "*.tif"));


txtpath=fullfile(DesDir, ['note.txt']);
fid=fopen(txtpath, 'w', 'n', 'US-ASCII');

% Loop
for ii=1:numel(files)
    filename=files(ii).name;
    filepath=fullfile(SouDir, filename);
    [~, fname, ext]=fileparts(filename);
    cr_folder=fullfile(DesDir, fname);
    strname=strsplit(fname, '_');
    strname=strname(end-2:end);
    strname=strjoin(strname, '_');

    if ~isfolder(cr_folder)
        mkdir(cr_folder);
    else
        cmd_rmdir(cr_folder);
        mkdir(cr_folder);
    end


    rows=['shapefiles\BL4rows_'];
    plots=['shapefiles\weeds_grassy_'];
    wfplots=['shapefiles\wf_grassy_'];
    samples=['shapefiles\BL_'];

    rows=[rows, strname, '.shp'];
    plots=[plots, strname, '.shp'];
    wfplots=[wfplots, strname, '.shp'];
    samples=[samples, strname, '.tif'];

    disp(['[', num2str(ii), '\', num2str(numel(files)), ']~', filename]);
    fprintf(fid, '%s\r\n', ['[', num2str(ii), '\', num2str(numel(files)), ']~', filename]);

    % Clip the BL/G community from the image
    simagepath=fullfile(cr_folder, ['BL_', strname, '.tif']);
    GenClip(rows, filepath, 0, simagepath);
    % Convert to the ordinary image
    tifpath=GenOrdTifImage(simagepath);

    % Create the Mask
    maskpaths=GenCompMark(simagepath, samples);









end


fprintf('Time Begin: ');
fprintf(str1);
fprintf('\n');


cur_data=date;
cur_time=fix(clock);
str2=sprintf('%s %.2d:%.2d:%.2d', cur_data, cur_time(4), cur_time(5), cur_time(6)); 
fprintf('Time End: ');
disp(str2);
timespan=toc(timebegin);
fprintf('Time Span: %.4f s\n', timespan);

disp('*******************************************************************');

function tifpath=GenOrdTifImage(inputpath)


    [srcdir, fname, ~]=fileparts(inputpath);
    tifpath=fullfile(srcdir, [fname, '_ordinary.tif']);


    image=imread(inputpath);


    imwrite(image, tifpath);

end



function GenClip(oneshp, filepath, BackVal, otpath)

    [~, fname, ~]=fileparts(oneshp);
    strcmd=['gdalwarp -of GTiff -cutline ', oneshp, ' -cl ', fname, ' -crop_to_cutline '];
    strcmd=[strcmd, '-dstnodata ' num2str(BackVal),' ', filepath, ' ', otpath];
    [~, cmdout]=system(strcmd);

end

function maskpaths=GenCompMark(filepath, samples)


    xlspath='classes.sets.xlsx';
    % Color plate
    uniValues=readcell(xlspath, 'Sheet', 'colorplate');
    uniValues(1, :)=[];
    uniValues(:, 1)=[];


    [soudir, fname, ~]=fileparts(filepath);
    maskpaths=fullfile(soudir, [fname, '_mask.tif']);

    sampimage=imread(samples);


    try
        [image, geo]=readgeoraster(filepath);
        try
            info=geotiffinfo(filepath);
        catch
            info=georasterinfo(filepath);
        end
    catch
        image=imread(filepath);
    end


    sampimage=GenFalse(sampimage);
    %% Use nearest neighbor classifier
    mask=GenNearestNeighborClass(image, sampimage);



    % rendering the mask
    outMat=zeros(size(mask, 1), size(mask, 2), 3);
    outMat=RenderUniValues(mask, uniValues, outMat);

    showmat=[image; outMat];
    % imshow(showmat);

    knn_euclidean=fullfile(soudir, [fname, '_knn_euclidean.png']);
    imwrite(showmat, knn_euclidean);
    

    try
        geotiffwrite(maskpaths, uint8(mask), geo);
    catch
        strcmd=['gdalinfo ', filepath];
        [~, cmdout]=system(strcmd);
        epsg=extractBetween(cmdout, "EPSG:"," got from GeoTIFF keys");
        epsg=epsg{1};
        % geotiffwrite(otpath, uint8(class_imag), geo, 'GeoKeyDirectoryTag', info.GeoTIFFTags.GeoKeyDirectoryTag);
        geotiffwrite(maskpaths, uint8(mask), geo, 'CoordRefSysCode', ['EPSG:', epsg]);
    end


    




end


function output=GenFalse(input)
    output=[];
    [rows, cols, ~]=size(input);
    values=unique(input(:));
    values(values>=100)=[];


    sample_regions=false([rows, cols, numel(values)]);


    % Loop to assign the matrixs
    for ii=1:numel(values)
        val=values(ii);
        index=find(input==val);
        band=sample_regions(:, :, ii);
        band(index)=1;
        sample_regions(:, :, ii)=band;

    end

    output=sample_regions;

end




function mask=GenNearestNeighborClass(image, sampimage)

    [rows, cols, ~]=size(image);

    %  Enhance the image**************************
    ycbcr=rgb2ycbcr(image);
    ycbcr(:, :, 1)=0;
    ycbcr=imadjust(ycbcr, stretchlim(ycbcr), []);

    % imwrite(ycbcr, 'ycbcr.tif');
    % *****************************************


    % classes={'soil', 'canola', 'soybean'};
    % nClasses=numel(classes);
    nClasses=size(sampimage, 3);
    % sample_regions=false([rows, cols, nClasses]);
    sample_regions=sampimage;

    mask=[];
    % select each sample region
    % figure;
    % imshow(image);
    % f=figure;
    % for ii=1:nClasses
    %     set(f, 'name', ['Select sample region for ', classes{ii}]);
    %     sample_regions(:, :, ii)=roipoly(image);
    % end
    % 
    % close(f);


    % Convert RGB to L*a*b colorspace
    lab=rgb2lab(image);
    % Calcualate the mean 'a*' and 'b*' value for each ROI area
    % a=lab(:, :, 2);
    % b=lab(:, :, 3);

    a=ycbcr(:, :, 2);
    b=ycbcr(:, :, 3);
    color_markers=repmat(0, [nClasses, 2]);

    for count=1:nClasses
        color_markers(count, 1)=mean2(a(sample_regions(:, :, count)));
        color_markers(count, 2)=mean2(b(sample_regions(:, :, count)));
    end


    % https://www.youtube.com/watch?v=3hEvcyCJNRc&list=PLEo-jHOqGNyUWoCSD3l3V-FjX9PnHvx5n&index=33
    % Classify each pixel using the nearest neighbor rule
    % Each class marker now has an 'a*' and 'b*' value.
    % You can classify each pixel in the |lab_x| image by calculating the
    % Euclidean distance bewteen that pixel and each marker. The smallest
    % distance will tell you that the pixel most closely matched that
    % marker. For example, if the distance between a pixel and the read
    % color marker is the smallest, then the pixel would be labeled as a
    % red pixel.


   color_labels=0:nClasses-1;
   a=double(a);
   b=double(b);
   distance=repmat(0, [size(a), nClasses]);

   % Perform classification
   for count=1:nClasses
       distance(:, :, count)=((a-color_markers(count, 1)).^2+...
           (b-color_markers(count, 2)).^2).^0.5;

   end

   % The other formulas as follows:
   % https://www.saedsayad.com/k_nearest_neighbors.htm

   [value, label]=min(distance, [], 3);
   label=color_labels(label);

   % clear value distance

   colors=[0, 0, 0; 0, 255, 0; 255, 0, 0];
   y=zeros(size(image));
   l=double(label)+1;

   for m=1:rows
       for n=1:cols
           y(m, n, :)=colors(l(m, n), :);

       end
   end



   mask=uint8(label);

end

No comments:

Post a Comment