Saturday, September 7, 2024

Friday, July 12, 2024

MATLAB: Layer Indices Calculation

#NDVI [2024-07-12] file.
#NDVI/ExG/GRVI/Edge/HSV/XYZ/NTSC/Lab/YCbCr [2024-07-18] file.
#NDVI/GNDVI/NDRE/ExG/GRVI/Edge/HSV/XYZ/NTSC/Lab/YCbCr [2024-08-27] file.

MATLAB: Row Detection Collections

[2024-07-11]files.

Thursday, July 4, 2024

MATLAB: Row Detection on the Image for Segmentation Using Hough Transform

[1] María Pérez-Ortiz, José Manuel Peña, Pedro Antonio Gutiérrez, Jorge Torres-Sánchez, César Hervás-Martínez, Francisca López-Granados. Selecting patterns and features for between- and within- crop-row weed mapping using UAV-imagery. Expert Systems with Applications, Volume 47, 2016, 85-94.

Wednesday, June 12, 2024

eCognition: Multiband Composite

 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
% Created by Author
% Version 1.0
% June 12, 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');



filepath='S2A_tile_20180201_18PVS.tif';
image=imread(filepath);
image=uint8(255.*rescale(image));
stdimage=double(image);

rgb=image(:, :, 1:3);
rgb=imadjust(rgb, stretchlim(rgb), []);
% imshow(rgb);


% Case_1: r(1/4)g(2)b(3)
c1_1=(stdimage(:, :, 1)+stdimage(:, :, 4))./2;
c1_1=uint8(c1_1);
c1=cat(3, c1_1, image(:, :, 2), image(:, :, 3));
c1=imadjust(c1, stretchlim(c1), []);
% imshow(c1);

% Case_2: r(3)g(4)b(1/4)
c2_1=(stdimage(:, :, 1)+stdimage(:, :, 4))./2;
c2_1=uint8(c2_1);
c2=cat(3, image(:, :, 3), image(:, :, 4), c2_1);
c2=imadjust(c2, stretchlim(c2), []);
% imshow(c2);

% Case_3: r(2)g(3)b(3/4)
c3_3=(stdimage(:, :, 3)+stdimage(:, :, 4))./2;
c3_3=uint8(c3_3);
c3=cat(3, image(:, :, 2), image(:, :, 3), c3_3);
c3=imadjust(c3, stretchlim(c3), []);
% imshow(c3);

comimage=[rgb, c1; c2, c3];

imwrite(comimage, 'comimage.png');


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('**********************************************************');

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

Saturday, April 6, 2024

ENVI: Instructions for converting ENVI format classification maps to GEOTIFF format

[1] Open the ENVI format classification image, such as image 2003; at this point, the image's save format is ENVI Classification, which can be checked by editing the image's header file (Edit Header). The method is to right-click on 2003 in the Available Bands List, and from the pop-up menu select Edit Header, as shown in the image below;
[2] In the Header Info dialog box, select TIFF from the File Type dropdown list and click OK. Afterward, the icon for 2003 changes, as shown below;
[3] In the ENVI main menu, select File->Save File As->TIFF/GEOTIFF, choose the output location in the dialog box, click OK to finish.

Thursday, February 29, 2024

Matlab: a simple approach for classifing two kinds of types on the image

It works well on small areas (here at the Plot level) and only with two types in the image that have significant color differences. File.
I added a loop to minimize the effect of the non-Rgeion of Interest on the binzrization process. 2nd. 3rd.
The conditions for applying the binary process are quite stringent. It's important to ensure that the image to be processed contains fairly typical features of the terrain colors and in appropriate quantities. Only then is it the right image to use, as this minimizes the area of invalid regions. 4th.
The calculation process completely excludes the background area. 5th.

Wednesday, February 28, 2024

Matlab: Convert RGB to HSV/XYZ/LAB/Ycbcr/NTSC

File. 2nd.
  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
% Created by LI Xu
% Version 1.0
% February 22, 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

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');

filename='wheat';

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

files=dir(SouDir);
files=files(3:end);


for ii=1:numel(files)
    % construct the input file path
    filepath=fullfile(SouDir, files(ii).name);

    [image, geo]=readgeoraster(filepath);
    image=double(image);

    try
        info=geotiffinfo(filepath);
    catch
        info=georasterinfo(filepath);
    end

    Num_bands=size(image, 3);

    if Num_bands==3
        RGB=image;
    else
        RGB=zeros(size(image, 1), size(image, 2), 3);
        RGB(:, :, 1)=image(:, :, 4);
        RGB(:, :, 2)=image(:, :, 2);
        RGB(:, :, 3)=image(:, :, 1);
    end

    % Normalise the RGB bands [0, 255]
    RGB=GenNormalise(RGB);


    % https://www.mathworks.com/help/images/understanding-color-spaces-and-color-space-conversion.html
    xyz=rgb2xyz(RGB);
    lab=rgb2lab(RGB);
    ycbcr=rgb2ycbcr(RGB);
    ntsc=rgb2ntsc(RGB);



    HSV=rgb2hsv(RGB);
    % ExG = 2 * G - R - B
    ExG=2*RGB(:, :, 2)-RGB(:, :, 1)-RGB(:, :, 3);



    otpath=strsplit(files(ii).name, '_');
    otpath=otpath(2:end);
    otpath=strjoin(otpath, '_');
    otpath_rgb=[filename, '_rgb_', otpath];
    otpath_hsv=[filename, '_hsv_', otpath];

    otpath_xyz=[filename, '_xyz_', otpath];
    otpath_lab=[filename, '_lab_', otpath];
    otpath_ycbcr=[filename, '_ycbcr_', otpath];
    otpath_ntsc=[filename, '_ntsc_', otpath];

    otpath_exg=[filename, '_exG_', otpath];


    otpath_rgb=fullfile(DesDir, otpath_rgb);
    otpath_hsv=fullfile(DesDir, otpath_hsv);
    otpath_xyz=fullfile(DesDir, otpath_xyz);
    otpath_lab=fullfile(DesDir, otpath_lab);
    otpath_ycbcr=fullfile(DesDir, otpath_ycbcr);
    otpath_ntsc=fullfile(DesDir, otpath_ntsc);
    otpath_exg=fullfile(DesDir, otpath_exg);


    try
        geotiffwrite(otpath_rgb, RGB, geo);
        geotiffwrite(otpath_hsv, HSV, geo);
        geotiffwrite(otpath_xyz, xyz, geo);
        geotiffwrite(otpath_lab, lab, geo);
        geotiffwrite(otpath_ycbcr, ycbcr, geo);
        geotiffwrite(otpath_ntsc, ntsc, geo);
        geotiffwrite(otpath_exg, ExG, 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(otpath_rgb, RGB, geo, 'CoordRefSysCode', ['EPSG:', epsg], 'TiffType', 'bigtiff');
        geotiffwrite(otpath_hsv, HSV, geo, 'CoordRefSysCode', ['EPSG:', epsg], 'TiffType', 'bigtiff');
        geotiffwrite(otpath_xyz, xyz, geo, 'CoordRefSysCode', ['EPSG:', epsg], 'TiffType', 'bigtiff');
        geotiffwrite(otpath_lab, lab, geo, 'CoordRefSysCode', ['EPSG:', epsg], 'TiffType', 'bigtiff');
        geotiffwrite(otpath_ycbcr, ycbcr, geo, 'CoordRefSysCode', ['EPSG:', epsg], 'TiffType', 'bigtiff');
        geotiffwrite(otpath_ntsc, ntsc, geo, 'CoordRefSysCode', ['EPSG:', epsg], 'TiffType', 'bigtiff');
        geotiffwrite(otpath_exg, ExG, geo, 'CoordRefSysCode', ['EPSG:', epsg], 'TiffType', 'bigtiff');
    end

    disp(['[', num2str(ii), '/', num2str(numel(files)), ']~', files(ii).name]);


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 output=GenNormalise(input)

    output=input*0;

    for ii=1:size(input, 3)
        image=input(:, :, ii);
        % red_normalized = (red - red.min()) / (red.max() - red.min()) * 255
        aa=image(:);
        image_normalized=(image-min(aa))./(max(aa)-min(aa))*255.0;
        output(:, :, ii)=image_normalized;



    end


end

Matlab: Decision Tree Tool for Image

This is a simple tool of decison tree for the image analysis. It can export the compared image and the ruleset file at once. File.

Tuesday, February 20, 2024

Canopeo: Green and Non-Green

I am using Canopeo here to calculate the percentage of green and non-green (RGB) in photos, and also to extract the green parts of the photos. Files. Delete the soil and everything else from the image.
[1] Canopeo.
[2] Andres Patrignani, Tyson E. Ochsner. 2015. Canopeo: A Powerful New Tool for Measuring Fractional Green Canopy Cover. Agronomy Journal, 107(6): 2312~2320.

Wednesday, February 7, 2024

Py+eCognition: Set up and tips

  1. Set up
  2. Hexagon_esgmentation_python_cp.dcp
  3. segment-anything.dcp
  4. How to download the latest version of eCognition? Click this link.
  5. How to install eCognition on Windows? Click this link for License Manager, click this link for Developer
  6. If you do not have a valid license, please request a trial version. Trial software access is not limited to a specific time period, but export and save functions, and the workspace environment are restricted. Rulesets saved in trial software cannot be opened in a fully-licensed version of eCognition software.
  7. From the Ground Up videos

Monday, February 5, 2024

ML: A simple SAM program from input image to output mask, saving as .tif format

 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
# https://github.com/facebookresearch/segment-anything/issues/221

import cv2, os
import matplotlib.pyplot as plt
sam_checkpoint='D:/PyTest/kkk/sam_vit_l_0b3195.pth'
model_type="vit_l"
from segment_anything import SamAutomaticMaskGenerator, sam_model_registry
sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)

inpath='D:/PyTest/kkk/dog.jpg'
img_arr=cv2.imread(inpath)
img_arr=cv2.cvtColor(img_arr,cv2.COLOR_BGR2RGB)

mask_generator=SamAutomaticMaskGenerator(sam)
# mask_generator = SamAutomaticMaskGenerator(
#     model=sam,
#     points_per_side=32,
#     pred_iou_thresh=0.86,
#     stability_score_thresh=0.92,
#     crop_n_layers=1,
#     crop_n_points_downscale_factor=2,
# #     # min_mask_region_area=100,  # Requires open-cv to run post-processing
# )
predictor=mask_generator.generate(img_arr)

# Choose the first mask
# mask=predictor[0]['segmentation']
# # Remove background by turn it to white
# img_arr[mask==False]=[255, 255, 255]


newimg = img_arr[:, :, 0] * 0
for ii in range(len(predictor)):
    # print(ii)
    mask=predictor[ii]['segmentation']
    # newimg = img_arr[:, :, 0] * 0
    newimg[mask == True] = ii+1
    # filename = os.path.join('D:/PyTest/kkk/export',str(ii+1)+'.tif')
    # cv2.imwrite(filename, newimg)

# plt.imshow(img_arr)
# plt.axis('off')
# plt.show()
filename='D:/PyTest/kkk/dog_new.tif'
cv2.imwrite(filename, newimg)