-
Notifications
You must be signed in to change notification settings - Fork 0
/
ml4qgis_algorithm.py
2098 lines (1802 loc) · 81.2 KB
/
ml4qgis_algorithm.py
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Ml4Qgis
A QGIS plugin
Machine learning in QGIS.
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2023-05-06
copyright : (C) 2023 by Mikhail Moskovchenko
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
__author__ = 'Mikhail Moskovchenko'
__date__ = '2023-05-06'
__copyright__ = '(C) 2023 by Mikhail Moskovchenko'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import shutil
import os
from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
QgsFeatureSink,
QgsProcessingAlgorithm,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterVectorLayer,
QgsProcessingParameterRasterLayer,
QgsProcessingParameterFile,
QgsProcessingParameterFolderDestination,
QgsProcessingParameterCrs,
QgsProcessingParameterString,
QgsProcessingParameterBoolean,
QgsProcessingParameterEnum,
QgsProcessingParameterNumber,
QgsProcessingParameterMultipleLayers,
QgsProcessingParameterFileDestination)
from .setup import check, docker_install, conda_install, python_install, getTempdir
from .preprocessing import sentinel2, landsat, mosaic, normalize
from .segmentation import seg_generate_tiles, seg_train, seg_test, seg_map
class DockerSetupAlgorithm(QgsProcessingAlgorithm):
"""
This is an example algorithm that takes a vector layer and
creates a new identical one.
It is meant to be used as an example of how to create your own
algorithms and explain methods and variables used to do it. An
algorithm like this will be available in all elements, and there
is not need for additional work.
All Processing algorithms should extend the QgsProcessingAlgorithm
class.
"""
def initAlgorithm(self, config):
"""
Here we define the inputs and output of the algorithm, along
with some other properties.
"""
self.addParameter(
QgsProcessingParameterString("-", "Don't mean anything at all", defaultValue="0")
)
def processAlgorithm(self, parameters, context, feedback):
"""
Here is where the processing itself takes place.
"""
docker_install(feedback)
return {}
def name(self):
"""
Returns the algorithm name, used for identifying the algorithm. This
string should be fixed for the algorithm, and must not be localised.
The name should be unique within each provider. Names should contain
lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'Install or repair Docker container'
def displayName(self):
"""
Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name.
"""
return self.tr(self.name())
def group(self):
"""
Returns the name of the group this algorithm belongs to. This string
should be localised.
"""
return self.tr(self.groupId())
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs to. This
string should be fixed for the algorithm, and must not be localised.
The group id should be unique within each provider. Group id should
contain lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'Setup'
def tr(self, string):
return QCoreApplication.translate('Processing', string)
def shortHelpString(self):
return 'ML4QGIS can use Docker backend for processing.\n \
That tool sets up the Docker image that contain the Python environment configured to do \
machine learning tasks. \n To use Docker backend you need to: \n \
1) Download Docker installer from <a href="https://www.docker.com">Docker official site</a>. \n \
2. Install Docker. \n 3. Run Docker. \n 4. Run this tool. \n \
Please always make sure that Docker is running every time you use any ML4QGIS script with Docker \
backend. \n We also recommend to use swap file because ML4QGIS scripts usually use lot of RAM.'
def createInstance(self):
return DockerSetupAlgorithm()
class CondaSetupAlgorithm(QgsProcessingAlgorithm):
"""
This is an example algorithm that takes a vector layer and
creates a new identical one.
It is meant to be used as an example of how to create your own
algorithms and explain methods and variables used to do it. An
algorithm like this will be available in all elements, and there
is not need for additional work.
All Processing algorithms should extend the QgsProcessingAlgorithm
class.
"""
def initAlgorithm(self, config):
"""
Here we define the inputs and output of the algorithm, along
with some other properties.
"""
self.addParameter(
QgsProcessingParameterFile(
'CONDAPATH',
self.tr('Conda folder'),
behavior = 1
)
)
self.addParameter(
QgsProcessingParameterString(
"ENV",
self.tr("Environment name"),
optional = True,
defaultValue = 'rsp'
)
)
def processAlgorithm(self, parameters, context, feedback):
"""
Here is where the processing itself takes place.
"""
path = self.parameterAsFile(parameters, 'CONDAPATH', context)
env = self.parameterAsString(parameters, 'ENV', context)
conda_install(path, env, feedback)
return {}
def name(self):
"""
Returns the algorithm name, used for identifying the algorithm. This
string should be fixed for the algorithm, and must not be localised.
The name should be unique within each provider. Names should contain
lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'Setup Conda access config'
def displayName(self):
"""
Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name.
"""
return self.tr(self.name())
def group(self):
"""
Returns the name of the group this algorithm belongs to. This string
should be localised.
"""
return self.tr(self.groupId())
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs to. This
string should be fixed for the algorithm, and must not be localised.
The group id should be unique within each provider. Group id should
contain lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'Setup'
def tr(self, string):
return QCoreApplication.translate('Processing', string)
def shortHelpString(self):
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'environment.yml')
return 'ML4QGIS can use Conda backend for processing.\n \
That tool sets up a config that will be used to access Conda env with installed requirements \
to run ML4QGIS scripts. You need to install Conda and set up the environment manually. \n \
1. Install <a href="https://www.anaconda.com/">Anaconda</a> or \
<a href="https://docs.conda.io/en/latest/miniconda.html">Miniconda</a>. \n \
2. Run a command "conda env create -f ' + path + '" or manually create Conda env that have \
<a href="https://remote-sensing-processor.readthedocs.io/en/latest/install.html">remote_sensing_processor</a> \
and all its dependencies installed. \n \
3. Select Conda folder destination. By default it is C:/Users/username/Anaconda3 or in \
C:/ProgramData/Anaconda3 on Windows, /home/username/anaconda/ on Linux and /Users/username/anaconda on Mac \
If you have installed miniconda, the folder will be named miniconda instead of anaconda. \n \
4. Define environment name. By default it is "rsp". \n 5. Run this tool.\n \
We also recommend to use swap file because ML4QGIS scripts usually use lot of RAM.'
def createInstance(self):
return CondaSetupAlgorithm()
class PythonSetupAlgorithm(QgsProcessingAlgorithm):
"""
This is an example algorithm that takes a vector layer and
creates a new identical one.
It is meant to be used as an example of how to create your own
algorithms and explain methods and variables used to do it. An
algorithm like this will be available in all elements, and there
is not need for additional work.
All Processing algorithms should extend the QgsProcessingAlgorithm
class.
"""
def initAlgorithm(self, config):
"""
Here we define the inputs and output of the algorithm, along
with some other properties.
"""
self.addParameter(
QgsProcessingParameterFile(
'PYTHONPATH',
self.tr('Python venv folder'),
behavior = 1
)
)
def processAlgorithm(self, parameters, context, feedback):
"""
Here is where the processing itself takes place.
"""
path = self.parameterAsFile(parameters, 'PYTHONPATH', context)
python_install(path, feedback)
return {}
def name(self):
"""
Returns the algorithm name, used for identifying the algorithm. This
string should be fixed for the algorithm, and must not be localised.
The name should be unique within each provider. Names should contain
lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'Setup Python access config'
def displayName(self):
"""
Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name.
"""
return self.tr(self.name())
def group(self):
"""
Returns the name of the group this algorithm belongs to. This string
should be localised.
"""
return self.tr(self.groupId())
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs to. This
string should be fixed for the algorithm, and must not be localised.
The group id should be unique within each provider. Group id should
contain lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'Setup'
def tr(self, string):
return QCoreApplication.translate('Processing', string)
def shortHelpString(self):
return 'ML4QGIS can use Python venv as a backend for processing.\n \
You need to set up the Python virtual environment configured to do machine learning tasks. \n \
1. Download and install <a href="https://www.python.org/">Python</a>. \n \
2. Create and activate new <a href="https://docs.python.org/3/library/venv.html">Virtual environment</a>. \n \
3. Install <a href="https://remote-sensing-processor.readthedocs.io/en/latest/install.html">remote_sensing_processor</a> \
and all its dependencies in a newly created venv. \n \
4. Select path to your venv. \n 5. Run this tool.\n \
We also recommend to use swap file because ML4QGIS scripts usually use lot of RAM. '
def createInstance(self):
return PythonSetupAlgorithm()
class TempDirAlgorithm(QgsProcessingAlgorithm):
"""
This is an example algorithm that takes a vector layer and
creates a new identical one.
It is meant to be used as an example of how to create your own
algorithms and explain methods and variables used to do it. An
algorithm like this will be available in all elements, and there
is not need for additional work.
All Processing algorithms should extend the QgsProcessingAlgorithm
class.
"""
def initAlgorithm(self, config):
"""
Here we define the inputs and output of the algorithm, along
with some other properties.
"""
self.addParameter(
QgsProcessingParameterFolderDestination(
"TEMP",
self.tr('Temporary directory'),
defaultValue = getTempdir()
)
)
def processAlgorithm(self, parameters, context, feedback):
"""
Here is where the processing itself takes place.
"""
outputDest = self.parameterAsString(parameters, "TEMP", context)
tempconfig = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tempdir.json')
with open(tempconfig, 'r') as f:
data = json.load(f)
data["tempdir"] = outputDest
with open(tempconfig, 'w') as f:
json.dump(data, f)
return {}
def name(self):
"""
Returns the algorithm name, used for identifying the algorithm. This
string should be fixed for the algorithm, and must not be localised.
The name should be unique within each provider. Names should contain
lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'Set temp directory'
def displayName(self):
"""
Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name.
"""
return self.tr(self.name())
def group(self):
"""
Returns the name of the group this algorithm belongs to. This string
should be localised.
"""
return self.tr(self.groupId())
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs to. This
string should be fixed for the algorithm, and must not be localised.
The group id should be unique within each provider. Group id should
contain lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'Setup'
def tr(self, string):
return QCoreApplication.translate('Processing', string)
def shortHelpString(self):
return 'ML4QGIS writes all used data to temporary directory to protect the original files from being damaged. \n \
The drive or volume where temporary directory is located must have enough free space.'
def createInstance(self):
return TempDirAlgorithm()
class Sentinel2Algorithm(QgsProcessingAlgorithm):
"""
This is an example algorithm that takes a vector layer and
creates a new identical one.
It is meant to be used as an example of how to create your own
algorithms and explain methods and variables used to do it. An
algorithm like this will be available in all elements, and there
is not need for additional work.
All Processing algorithms should extend the QgsProcessingAlgorithm
class.
"""
# Constants used to refer to parameters and outputs. They will be
# used when calling the algorithm from another algorithm, or when
# calling from the QGIS console.
OUTPUT = 'OUTPUT'
INPUT = 'INPUT'
def initAlgorithm(self, config):
"""
Here we define the inputs and output of the algorithm, along
with some other properties.
"""
self.addParameter(
QgsProcessingParameterEnum(
"BACKEND",
"Backend",
options=['Python venv', 'Conda', 'Docker container'],
defaultValue = 0
)
)
# We add the input vector features source. It can have any kind of
# geometry.
self.addParameter(
QgsProcessingParameterFile(
self.INPUT,
self.tr('Input archive'),
extension = 'zip'
)
)
self.addParameter(
QgsProcessingParameterBoolean(
"SEN2COR",
"Sen2cor atmospheric correction",
defaultValue = True,
optional = True
)
)
self.addParameter(
QgsProcessingParameterBoolean(
"SUPERRES",
"Super Resolution (uses GPU)",
defaultValue = True,
optional = True
)
)
self.addParameter(
QgsProcessingParameterBoolean(
"CLOUDMASK",
"Mask clouds",
defaultValue = True,
optional = True
)
)
self.addParameter(
QgsProcessingParameterCrs(
"CRS",
"CRS",
optional = True
)
)
self.addParameter(
QgsProcessingParameterVectorLayer(
'CLIP',
'Vector layer to clip by',
[QgsProcessing.TypeVectorPolygon],
optional = True
)
)
# We add a feature sink in which to store our processed features (this
# usually takes the form of a newly created vector layer when the
# algorithm is run in QGIS).
self.addParameter(
QgsProcessingParameterFolderDestination(
self.OUTPUT,
self.tr('Output folder')
)
)
def processAlgorithm(self, parameters, context, feedback):
"""
Here is where the processing itself takes place.
"""
backend = self.parameterAsEnum(parameters, "BACKEND", context)
backend = ['python', 'conda', 'docker'][backend]
inputLayer = self.parameterAsFile(parameters, self.INPUT, context)
inputSen2Cor = self.parameterAsBool(parameters, "SEN2COR", context)
inputSuperRes = self.parameterAsBool(parameters, "SUPERRES", context)
inputCloudMask = self.parameterAsBool(parameters, "CLOUDMASK", context)
#inputClip = self.parameterAsSource(parameters, "CLIP", context)
inputClip = self.parameterAsVectorLayer(parameters, "CLIP", context)
outputCrs = self.parameterAsCrs(parameters, "CRS", context)
outputDest = self.parameterAsString(parameters, self.OUTPUT, context)
sentinel2(backend, inputLayer, inputSen2Cor, inputSuperRes, inputCloudMask, inputClip, outputCrs, outputDest, feedback)
return {self.OUTPUT: outputDest}
def name(self):
"""
Returns the algorithm name, used for identifying the algorithm. This
string should be fixed for the algorithm, and must not be localised.
The name should be unique within each provider. Names should contain
lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'Sentinel-2 preprocessing'
def displayName(self):
"""
Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name.
"""
return self.tr(self.name())
def group(self):
"""
Returns the name of the group this algorithm belongs to. This string
should be localised.
"""
return self.tr(self.groupId())
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs to. This
string should be fixed for the algorithm, and must not be localised.
The group id should be unique within each provider. Group id should
contain lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'Preprocessing'
def tr(self, string):
return QCoreApplication.translate('Processing', string)
def shortHelpString(self):
return 'Preprocess Sentinel-2 imagery. \n \
Backend: select a backend to run script. \n \
Input archive: a path to Sentinel-2 zip archive. \n \
Sen2Cor atmospheric correction: To perform a sen2cor atmospheric correction you need to have Sen2Cor installed. \
Required version is 2.11 for Windows and Linux and 2.9 for Mac OS. Here is an \
<a href="http://wiki.awf.forst.uni-goettingen.de/wiki/index.php/Installation_of_SNAP">instruction</a> \
how to install it. \n \
Super Resolution: Is upscaling 20- and 60-m bands to 10 m resolution needed. \
May run very slow if GPU does not support CUDA. \n \
Mask clouds: removes clouds from image. \n \
CRS: you can define projection in which output data should be. \n \
Vector layer to clip by: path to vector file to be used to crop the image. \n \
Output folder: directory where preprocessed image will be saved.'
def createInstance(self):
return Sentinel2Algorithm()
class LandsatAlgorithm(QgsProcessingAlgorithm):
"""
This is an example algorithm that takes a vector layer and
creates a new identical one.
It is meant to be used as an example of how to create your own
algorithms and explain methods and variables used to do it. An
algorithm like this will be available in all elements, and there
is not need for additional work.
All Processing algorithms should extend the QgsProcessingAlgorithm
class.
"""
# Constants used to refer to parameters and outputs. They will be
# used when calling the algorithm from another algorithm, or when
# calling from the QGIS console.
OUTPUT = 'OUTPUT'
INPUT = 'INPUT'
def initAlgorithm(self, config):
"""
Here we define the inputs and output of the algorithm, along
with some other properties.
"""
self.addParameter(
QgsProcessingParameterEnum(
"BACKEND",
"Backend",
options=['Python venv', 'Conda', 'Docker container'],
defaultValue = 0
)
)
# We add the input vector features source. It can have any kind of
# geometry.
self.addParameter(
QgsProcessingParameterFile(
self.INPUT,
self.tr('Input archive'),
fileFilter = 'Landsat archives(*.tar *.tar.gz)'
)
)
self.addParameter(
QgsProcessingParameterCrs(
"CRS",
"CRS",
optional = True
)
)
self.addParameter(
QgsProcessingParameterBoolean(
"CLOUDMASK",
"Mask clouds",
defaultValue = True,
optional = True
)
)
self.addParameter(
QgsProcessingParameterBoolean(
"PANSHARPEN",
"Pansharpen",
defaultValue = True,
optional = True
)
)
self.addParameter(
QgsProcessingParameterBoolean(
"KEEP_PAN",
"Keep pansharpening band",
defaultValue = False,
optional = True
)
)
self.addParameter(
QgsProcessingParameterEnum(
"RESAMPLING",
"Resampling algorithm",
options=['bilinear', 'cubic', 'cubic_spline', 'lanczos', 'average', 'mode', 'max', 'min', 'med', 'q1', 'q3', 'sum', 'rms', 'nearest'],
defaultValue = 0,
optional = True
)
)
self.addParameter(
QgsProcessingParameterEnum(
"TEMPERATURE",
"Temperature units",
options=['k', 'c'],
defaultValue = 0,
optional = True
)
)
self.addParameter(
QgsProcessingParameterVectorLayer(
'CLIP',
'Vector layer to clip by',
[QgsProcessing.TypeVectorPolygon],
optional = True
)
)
# We add a feature sink in which to store our processed features (this
# usually takes the form of a newly created vector layer when the
# algorithm is run in QGIS).
self.addParameter(
QgsProcessingParameterFolderDestination(
self.OUTPUT,
self.tr('Output folder')
)
)
def processAlgorithm(self, parameters, context, feedback):
"""
Here is where the processing itself takes place.
"""
backend = self.parameterAsEnum(parameters, "BACKEND", context)
backend = ['python', 'conda', 'docker'][backend]
inputLayer = self.parameterAsFile(parameters, self.INPUT, context)
inputCloudMask = self.parameterAsBool(parameters, "CLOUDMASK", context)
inputPansharpen = self.parameterAsBool(parameters, "PANSHARPEN", context)
inputKeepPan = self.parameterAsBool(parameters, "KEEP_PAN", context)
inputResampling = self.parameterAsEnum(parameters, "RESAMPLING", context)
inputResampling = ['bilinear', 'cubic', 'cubic_spline', 'lanczos', 'average', 'mode', 'max', 'min', 'med', 'q1', 'q3', 'sum', 'rms', 'nearest'][inputResampling]
inputTemperature = self.parameterAsEnum(parameters, "TEMPERATURE", context)
inputTemperature = ['k', 'c'][inputTemperature]
#inputClip = self.parameterAsSource(parameters, "CLIP", context)
inputClip = self.parameterAsVectorLayer(parameters, "CLIP", context)
outputCrs = self.parameterAsCrs(parameters, "CRS", context)
outputDest = self.parameterAsString(parameters, self.OUTPUT, context)
landsat(backend, inputLayer, inputCloudMask, inputPansharpen, inputKeepPan, inputResampling, inputTemperature, inputClip, outputCrs, outputDest, feedback)
return {self.OUTPUT: outputDest}
def name(self):
"""
Returns the algorithm name, used for identifying the algorithm. This
string should be fixed for the algorithm, and must not be localised.
The name should be unique within each provider. Names should contain
lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'Landsat preprocessing'
def displayName(self):
"""
Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name.
"""
return self.tr(self.name())
def group(self):
"""
Returns the name of the group this algorithm belongs to. This string
should be localised.
"""
return self.tr(self.groupId())
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs to. This
string should be fixed for the algorithm, and must not be localised.
The group id should be unique within each provider. Group id should
contain lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'Preprocessing'
def tr(self, string):
return QCoreApplication.translate('Processing', string)
def shortHelpString(self):
return 'Preprocess Landsat imagery. \n \
Backend: select a backend to run script. \n \
Input archive: a path to Landsat tar or tar.gz archive. \n \
CRS: you can define projection in which output data should be. \n \
Mask clouds: removes clouds from image. \n \
Pansharpen: is pansharpening needed. Brovey transform is used for pansharpening Landsat 7, 8 and 9. \n \
Keep pansharpening band: keep pansharpening band or delete it. Pansharpening band have the same \
wavelengths as optical bands, so it does not contain any additional information to other bands.\
Affects only Landsat 7, 8 and 9. \n \
Resampling algorithm: resampling method that will be used to upscale bands that cannot be \
upscaled in pansharpening operation. Affects only Landsat 7, 8 and 9. \n \
Temperature units: convert thermal band to kelvins or celsius (no farenheit lol). \n \
Vector layer to clip by: path to vector file to be used to crop the image. \n \
Output folder: directory where preprocessed image will be saved.'
def createInstance(self):
return LandsatAlgorithm()
class MosaicAlgorithm(QgsProcessingAlgorithm):
"""
This is an example algorithm that takes a vector layer and
creates a new identical one.
It is meant to be used as an example of how to create your own
algorithms and explain methods and variables used to do it. An
algorithm like this will be available in all elements, and there
is not need for additional work.
All Processing algorithms should extend the QgsProcessingAlgorithm
class.
"""
# Constants used to refer to parameters and outputs. They will be
# used when calling the algorithm from another algorithm, or when
# calling from the QGIS console.
OUTPUT = 'OUTPUT'
INPUT = 'INPUT'
def initAlgorithm(self, config):
"""
Here we define the inputs and output of the algorithm, along
with some other properties.
"""
self.addParameter(
QgsProcessingParameterEnum(
"BACKEND",
"Backend",
options=['Python venv', 'Conda', 'Docker container'],
defaultValue = 0
)
)
self.addParameter(
QgsProcessingParameterBoolean(
"MB",
"Multi-band rasters (Sentinel-2, Landsat etc.)",
defaultValue = False
)
)
# We add the input vector features source. It can have any kind of
# geometry.
self.addParameter(
QgsProcessingParameterMultipleLayers(
self.INPUT,
self.tr("Input rasters"),
QgsProcessing.TypeFile
)
)
self.addParameter(
QgsProcessingParameterBoolean(
"FILL",
"Fill nodata",
defaultValue = False,
optional = True
)
)
self.addParameter(
QgsProcessingParameterNumber(
"DISTANCE",
"Fill distance",
defaultValue = 250,
optional = True
)
)
self.addParameter(
QgsProcessingParameterVectorLayer(
'CLIP',
'Vector layer to clip by',
[QgsProcessing.TypeVectorPolygon],
optional = True
)
)
self.addParameter(
QgsProcessingParameterCrs(
"CRS",
"CRS",
optional = True
)
)
self.addParameter(
QgsProcessingParameterNumber(
"NODATA",
"Nodata value",
optional = True
)
)
self.addParameter(
QgsProcessingParameterRasterLayer(
"REFERENCE",
'Reference raster',
optional = True
)
)
self.addParameter(
QgsProcessingParameterEnum(
"RESAMPLING",
"Resampling algorithm",
options=['bilinear', 'cubic', 'cubic_spline', 'lanczos', 'average', 'mode', 'max', 'min', 'med', 'q1', 'q3', 'sum', 'rms', 'nearest'],
defaultValue = 4,
optional = True
)
)
self.addParameter(
QgsProcessingParameterBoolean(
"ORDER",
"Stack raster in order from more to less nodata",
defaultValue = False,
optional = True
)
)
self.addParameter(
QgsProcessingParameterBoolean(
"KEEP",
"Keep all Landsat channels",
defaultValue = True,
optional = True
)
)
# We add a feature sink in which to store our processed features (this
# usually takes the form of a newly created vector layer when the
# algorithm is run in QGIS).
self.addParameter(
QgsProcessingParameterFolderDestination(
self.OUTPUT,
self.tr('Output folder')
)
)
def processAlgorithm(self, parameters, context, feedback):
"""
Here is where the processing itself takes place.
"""
backend = self.parameterAsEnum(parameters, "BACKEND", context)
backend = ['python', 'conda', 'docker'][backend]
inputMultiBand = self.parameterAsBool(parameters, "MB", context)
inputLayers = self.parameterAsFileList(parameters, self.INPUT, context)
inputFill = self.parameterAsBool(parameters, "FILL", context)
inputFillDistance = self.parameterAsInt(parameters, "DISTANCE", context)
inputClip = self.parameterAsVectorLayer(parameters, "CLIP", context)
outputCrs = self.parameterAsCrs(parameters, "CRS", context)
#inputNodata = self.parameterAsInt(parameters, "NODATA", context)
inputNodata = parameters['NODATA']
inputReference = self.parameterAsFile(parameters, "REFERENCE", context)
inputResampling = self.parameterAsEnum(parameters, "RESAMPLING", context)
inputResampling = ['bilinear', 'cubic', 'cubic_spline', 'lanczos', 'average', 'mode', 'max', 'min', 'med', 'q1', 'q3', 'sum', 'rms', 'nearest'][inputResampling]
inputNodataOrder = self.parameterAsBool(parameters, "ORDER", context)
inputKeepAllChannels = self.parameterAsBool(parameters, "KEEP", context)
outputDest = self.parameterAsString(parameters, self.OUTPUT, context)
mosaic(backend, inputMultiBand, inputLayers, inputFill, inputFillDistance, inputClip, outputCrs, inputNodata, inputReference, inputResampling, inputNodataOrder, inputKeepAllChannels, outputDest, feedback)
return {self.OUTPUT: outputDest}
def name(self):
"""
Returns the algorithm name, used for identifying the algorithm. This
string should be fixed for the algorithm, and must not be localised.
The name should be unique within each provider. Names should contain
lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'Create raster mosaic'
def displayName(self):
"""
Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name.
"""
return self.tr(self.name())
def group(self):
"""
Returns the name of the group this algorithm belongs to. This string
should be localised.
"""
return self.tr(self.groupId())
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs to. This
string should be fixed for the algorithm, and must not be localised.
The group id should be unique within each provider. Group id should
contain lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'Preprocessing'
def tr(self, string):
return QCoreApplication.translate('Processing', string)