Showing posts with label Matlab. Show all posts
Showing posts with label Matlab. Show all posts

Monday, March 9, 2026

Matlab: Compress the file size for gif files

% ────────────────────────────────────────────────
% Compress large GIF → smaller GIF (same size, fewer colors)
% ────────────────────────────────────────────────

inputGif  = 'original.gif';      % ← change this
outputGif = 'compressed_version.gif';

[frames, map] = imread(inputGif, 'Frames', 'all');

if size(frames,3) == 3
    isRGB = true;
else
    isRGB = false;
end

nFrames = size(frames, 4);

% ── Super aggressive settings ──
nColors     = 16;          % try 12 or 8 if still too big
useDither   = false;       % no dither = smaller
delayFactor = 4.0;         % 4× slower → big size win
frameStep   = 3;           % keep only every 3rd frame (big reduction)

newFrames = cell(1, floor(nFrames / frameStep));
globalMap = [];

k = 1;
for i = 1:frameStep:nFrames
    if isRGB
        thisFrame = frames(:,:,:,i);
    else
        thisIndexed = frames(:,:,:,i);
        thisFrame   = ind2rgb(thisIndexed, map);
    end
    
    if k == 1
        if useDither
            [indexed, globalMap] = rgb2ind(thisFrame, nColors);
        else
            [indexed, globalMap] = rgb2ind(thisFrame, nColors, 'nodither');
        end
    else
        if useDither
            indexed = rgb2ind(thisFrame, globalMap);
        else
            indexed = rgb2ind(thisFrame, globalMap, 'nodither');
        end
    end
    
    newFrames{k} = indexed;
    k = k + 1;
end

% Timing – slow it down a lot
info      = imfinfo(inputGif);
origDelay = info(1).DelayTime / 100;
newDelay  = origDelay * delayFactor;
if newDelay < 0.05, newDelay = 0.05; end  % reasonable min

% Write
imwrite(newFrames{1}, globalMap, outputGif, 'gif', ...
    'LoopCount', Inf, ...
    'DelayTime', newDelay);

for kk = 2:numel(newFrames)
    imwrite(newFrames{kk}, globalMap, outputGif, 'gif', ...
        'WriteMode', 'append', ...
        'DelayTime', newDelay);
end

% Report
origSize = dir(inputGif).bytes  / 1e6;
newSize  = dir(outputGif).bytes / 1e6;
fprintf('MATLAB: %.0f MB → %.0f MB (%.0f%% smaller)\n', origSize, newSize, (origSize-newSize)/origSize*100);
disp(['Saved: ' outputGif]);

Thursday, July 31, 2025

Data: GOES-16 True Color Images over Southern Manitoba

The active operational time range for GOES-16 as GOES-East was December 18, 2017, to April 4, 2025. During this period, it provided continuous imagery and data, including ABI (Advanced Baseline Imager) bands used for RGB composites like GeoColor, which you’re interested in.code. Tool.

Monday, March 24, 2025

Matlab: 本地部署Deepseek,对话模式

一、下载Ollama,修改默认安装路径
二、本地部署模型
三、MATLAB安装LLMs
四、Matlab检测代码

一、下载Ollama,修改默认安装路径

Ollama 是一个可以让你使用并管理 AI 模型的工具,相当于 R1 的承载器具,因此我们在本地部署模型前必须先安装 Ollama。打开 「Ollama 官网:」https://ollama.com/,点击“Download”。
选择适合你电脑的版本,例如“「Windows」”点击“「Download for Windows」”。
安装到指定的路径
下载完成后,双击安装,默认会装到C盘。通过如下方式修改,举例:我想安装在D:\Ollama
  1. 把下载的安装包放在D:\Ollama下
  2. 在D:\Ollama下,打开cmd,输入此命令敲回车即可 OllamaSetup.exe /DIR="D:\Ollama"
  3. 此时就可以看到Ollama被安装到指定路径了。(如果你下载完直接点了安装,也不用担心,直接控制面板程序卸载,卸载了,重新安装即可)

二、本地部署模型

  1. 部署之前,增加环境变量
  2. 增加这个环境变量的话,下载的模型会存储在此,避免占用C盘内存。 注意:增加后,重启电脑以确保生效。
  3. 本地部署deepseek模型
  4. 在cmd下输入命令③代码,即可安装。

      三、MATLAB安装LLMs

      打开网页,添加此到当前Matlab。

      四、Matlab检测代码

      第一步,现在cmd里面运行部署的模型ollama run deepseek-r1:14b。
      第二步,matlab中运行:file

      References

Monday, March 3, 2025

Matlab: Export the selected polygons from the Shapefile

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
% Shp Path
shppath='NFDB_poly_20210707.shp';
S = readgeotable(shppath);
[~, prjname, ~]=fileparts(shppath);
prjpath=[prjname, '.prj'];

% Example: Select polygons where 'LandType' is 'Forest' and 'Area' > 1000
selected_rows = S(S.SRC_AGENCY == "MB" & S.YEAR ==2017, :);


% Loop
for ii=5:10
    rows=selected_rows(selected_rows.MONTH==ii, :);


    otpath=2017*100+ii;
    copyfile(prjpath, [num2str(otpath), '.prj']);
    otpath=[num2str(otpath), '.shp'];

    shapewrite(rows, otpath);
    

end

Wednesday, February 26, 2025

Data: Purple Air Data

File. V2
  1. https://www2.purpleair.com/
  2. https://api.purpleair.com/#api-sensors-get-sensors-data
  3. https://develop.purpleair.com/dashboards/organization
  4. https://cyclone.unbc.ca/aqmap/data/AQCSV/

Monday, February 17, 2025

Matlab: Batch Mapping

This program requires all images and shapefiles to be in a **Geographic Coordinate System**.
Mapping with a large number of latitude and longitude points.

Wednesday, February 12, 2025

Matlab: MCD64A1

This program can extract burnt locations from MCD64A1 products. file.

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.

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.

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