Esempio n. 1
0
    def testImportIntoGpkg(self):
        # init target file
        test_gpkg = tempfile.mktemp(suffix='.gpkg', dir=self.testDataDir)
        gdal.GetDriverByName('GPKG').Create(test_gpkg, 1, 1, 1)
        source = QgsRasterLayer(os.path.join(self.testDataDir, 'raster', 'band3_byte_noct_epsg4326.tif'), 'my', 'gdal')
        self.assertTrue(source.isValid())
        provider = source.dataProvider()
        fw = QgsRasterFileWriter(test_gpkg)
        fw.setOutputFormat('gpkg')
        fw.setCreateOptions(['RASTER_TABLE=imported_table', 'APPEND_SUBDATASET=YES'])

        pipe = QgsRasterPipe()
        self.assertTrue(pipe.set(provider.clone()))

        projector = QgsRasterProjector()
        projector.setCrs(provider.crs(), provider.crs())
        self.assertTrue(pipe.insert(2, projector))

        self.assertEqual(fw.writeRaster(pipe,
                                        provider.xSize(),
                                        provider.ySize(),
                                        provider.extent(),
                                        provider.crs()), 0)

        # Check that the test geopackage contains the raster layer and compare
        rlayer = QgsRasterLayer('GPKG:%s:imported_table' % test_gpkg)
        self.assertTrue(rlayer.isValid())
        out_provider = rlayer.dataProvider()
        self.assertEqual(provider.block(1, provider.extent(), source.width(), source.height()).data(),
                         out_provider.block(1, out_provider.extent(), rlayer.width(), rlayer.height()).data())

        # remove result file
        os.unlink(test_gpkg)
Esempio n. 2
0
    def testImportIntoGpkg(self):
        # init target file
        test_gpkg = tempfile.mktemp(suffix='.gpkg', dir=self.testDataDir)
        gdal.GetDriverByName('GPKG').Create(test_gpkg, 1, 1, 1)
        source = QgsRasterLayer(os.path.join(self.testDataDir, 'raster', 'band3_byte_noct_epsg4326.tif'), 'my', 'gdal')
        self.assertTrue(source.isValid())
        provider = source.dataProvider()
        fw = QgsRasterFileWriter(test_gpkg)
        fw.setOutputFormat('gpkg')
        fw.setCreateOptions(['RASTER_TABLE=imported_table', 'APPEND_SUBDATASET=YES'])

        pipe = QgsRasterPipe()
        self.assertTrue(pipe.set(provider.clone()))

        projector = QgsRasterProjector()
        projector.setCrs(provider.crs(), provider.crs())
        self.assertTrue(pipe.insert(2, projector))

        self.assertEqual(fw.writeRaster(pipe,
                                        provider.xSize(),
                                        provider.ySize(),
                                        provider.extent(),
                                        provider.crs()), 0)

        # Check that the test geopackage contains the raster layer and compare
        rlayer = QgsRasterLayer('GPKG:%s:imported_table' % test_gpkg)
        self.assertTrue(rlayer.isValid())
        out_provider = rlayer.dataProvider()
        self.assertEqual(provider.block(1, provider.extent(), source.width(), source.height()).data(),
                         out_provider.block(1, out_provider.extent(), rlayer.width(), rlayer.height()).data())

        # remove result file
        os.unlink(test_gpkg)
Esempio n. 3
0
    def replaceImage(self, filepath, title):
        self.title = title
        self.filepath = filepath

        # set custom properties
        self.setCustomProperty("title", title)
        self.setCustomProperty("filepath", self.filepath)
        self.setName(title)

        fileInfo = QFileInfo(filepath)
        ext = fileInfo.suffix()
        if ext == "pdf":
            s = QSettings()
            oldValidation = s.value("/Projections/defaultBehavior")
            s.setValue("/Projections/defaultBehavior",
                       "useGlobal")  # for not asking about crs
            path = fileInfo.filePath()
            baseName = fileInfo.baseName()
            layer = QgsRasterLayer(path, baseName)
            self.image = layer.previewAsImage(
                QSize(layer.width(), layer.height()))
            s.setValue("/Projections/defaultBehavior", oldValidation)
        else:
            reader = QImageReader(filepath)
            self.image = reader.read()
        self.repaint()
Esempio n. 4
0
    def calc_11_e(self, dir_output, dir_pv, dir_c_kecil_11, temp_folder,
                  val_tir2emissivitys, val_tir2emissivityv):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_pv = dir_pv
        self.dir_c_kecil_11 = dir_c_kecil_11
        self.dir_output_temp = self.path + '11 - e.tif'

        self.val_tir2emissivitys = val_tir2emissivitys
        self.val_tir2emissivityv = val_tir2emissivityv

        entries = []

        pv = QgsRasterLayer(self.dir_pv)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'Pv@1'
        ras.raster = pv
        ras.bandNumber = 1
        entries.append(ras)

        c_kecil_11 = QgsRasterLayer(self.dir_c_kecil_11)
        ras = QgsRasterCalculatorEntry()
        ras.ref = '11 - c kecil@1'
        ras.raster = c_kecil_11
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator(
                str(self.val_tir2emissivityv) + ' * "Pv@1" + ' +
                str(self.val_tir2emissivitys) +
                ' * ( 1 - "Pv@1" ) + "11 - c kecil@1"', self.dir_output_temp,
                'GTiff', c_kecil_11.extent(), c_kecil_11.width(),
                c_kecil_11.height(), entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator(
                str(self.val_tir2emissivityv) + ' * "Pv@1" + ' +
                str(self.val_tir2emissivitys) +
                ' * ( 1 - "Pv@1" ) + "11 - c kecil@1"', self.dir_output,
                'GTiff', c_kecil_11.extent(), c_kecil_11.width(),
                c_kecil_11.height(), entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
    def testExportToGpkgWithExtraExtentNoNoData(self):
        tmpName = tempfile.mktemp(suffix='.gpkg')
        # Remove nodata
        gdal.Translate('/vsimem/src.tif',
                       os.path.join(self.testDataDir, 'raster',
                                    'band3_byte_noct_epsg4326.tif'),
                       options='-a_nodata none')
        source = QgsRasterLayer('/vsimem/src.tif', 'my', 'gdal')
        self.assertTrue(source.isValid())
        provider = source.dataProvider()
        fw = QgsRasterFileWriter(tmpName)
        fw.setOutputFormat('gpkg')

        pipe = QgsRasterPipe()
        self.assertTrue(pipe.set(provider.clone()))

        self.assertEqual(
            fw.writeRaster(pipe,
                           provider.xSize() + 4,
                           provider.ySize() + 4,
                           QgsRectangle(-3 - 2, -4 - 2, 7 + 2, 6 + 2),
                           provider.crs()), 0)
        del fw

        # Check that the test geopackage contains the raster layer and compare
        rlayer = QgsRasterLayer(tmpName)
        self.assertTrue(rlayer.isValid())
        out_provider = rlayer.dataProvider()
        for i in range(3):
            src_data = provider.block(i + 1, provider.extent(), source.width(),
                                      source.height())
            out_data = out_provider.block(i + 1, provider.extent(),
                                          source.width(), source.height())
            self.assertEqual(src_data.data(), out_data.data())
        out_data = out_provider.block(1, QgsRectangle(7, -4, 7 + 2, 6), 2, 8)
        # No nodata: defaults to zero
        self.assertEqual(out_data.data().data(), b'\x00' * 2 * 8)
        del out_provider
        del rlayer

        # remove result file
        gdal.Unlink('/vsimem/src.tif')
        os.unlink(tmpName)
Esempio n. 6
0
    def calc_a0(self, dir_output, dir_E1, dir_E2, temp_folder, A10, A11):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_E1 = dir_E1
        self.dir_E2 = dir_E2
        self.dir_output_temp = self.path + 'A0.tif'

        self.A10 = A10
        self.A11 = A11

        entries = []

        E1 = QgsRasterLayer(self.dir_E1)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'E1@1'
        ras.raster = E1
        ras.bandNumber = 1
        entries.append(ras)

        E2 = QgsRasterLayer(self.dir_E2)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'E2@1'
        ras.raster = E2
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator(
                '"E1@1" * ' + self.A10 + ' + "E2@1" * ' + self.A11,
                self.dir_output_temp, 'GTiff', E2.extent(), E2.width(),
                E2.height(), entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator(
                '"E1@1" * ' + self.A10 + ' + "E2@1" * ' + self.A11,
                self.dir_output, 'GTiff', E2.extent(), E2.width(), E2.height(),
                entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 7
0
    def calc_11_ckecil(self, dir_output, dir_pv, temp_folder,
                       val_tir2emissivitys, val_tir2emissivityv,
                       val_geometrical):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_pv = dir_pv
        self.dir_output_temp = self.path + '11 - c kecil.tif'

        self.val_tir2emissivitys = val_tir2emissivitys
        self.val_tir2emissivityv = val_tir2emissivityv
        self.val_geometrical = val_geometrical

        entries = []

        pv = QgsRasterLayer(self.dir_pv)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'Pv@1'
        ras.raster = pv
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator(
                '( 1 - ' + str(self.val_tir2emissivitys) + ' ) * ' +
                str(self.val_tir2emissivityv) + ' * ' +
                str(self.val_geometrical) + ' * ( 1 - "Pv@1" )',
                self.dir_output_temp, 'GTiff', pv.extent(), pv.width(),
                pv.height(), entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator(
                '( 1 - ' + str(self.val_tir2emissivitys) + ' ) * ' +
                str(self.val_tir2emissivityv) + ' * ' +
                str(self.val_geometrical) + ' * ( 1 - "Pv@1" )',
                self.dir_output, 'GTiff', pv.extent(), pv.width(), pv.height(),
                entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 8
0
    def calc_pv(self, dir_output, dir_ndvi, temp_folder, val_ndvis, val_ndviv):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_ndvi = dir_ndvi
        self.dir_output_temp = self.path + 'Pv.tif'

        self.val_ndvis = val_ndvis
        self.val_ndviv = val_ndviv

        entries = []

        ndvi = QgsRasterLayer(self.dir_ndvi)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'ndvi@1'
        ras.raster = ndvi
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator(
                '( ( "ndvi@1" - ' + str(self.val_ndvis) + ' ) / ( ' +
                str(self.val_ndviv) + ' - ' + str(self.val_ndvis) +
                ' ) ) * ( ( "ndvi@1" - ' + str(self.val_ndvis) + ' ) / ( ' +
                str(self.val_ndviv) + ' - ' + str(self.val_ndvis) + ' ) )',
                self.dir_output_temp, 'GTiff', ndvi.extent(), ndvi.width(),
                ndvi.height(), entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator(
                '( ( "ndvi@1" - ' + str(self.val_ndvis) + ' ) / ( ' +
                str(self.val_ndviv) + ' - ' + str(self.val_ndvis) +
                ' ) ) * ( ( "ndvi@1" - ' + str(self.val_ndvis) + ' ) / ( ' +
                str(self.val_ndviv) + ' - ' + str(self.val_ndvis) + ' ) )',
                self.dir_output, 'GTiff', ndvi.extent(), ndvi.width(),
                ndvi.height(), entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 9
0
    def calc_a2(self, dir_output, dir_A, dir_E2, temp_folder, B11):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_A = dir_A
        self.dir_E2 = dir_E2
        self.dir_output_temp = self.path + 'A2.tif'

        self.B11 = B11

        entries = []

        A = QgsRasterLayer(self.dir_A)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'A@1'
        ras.raster = A
        ras.bandNumber = 1
        entries.append(ras)

        E2 = QgsRasterLayer(self.dir_E2)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'E2@1'
        ras.raster = E2
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator('"A@1" + "E2@1" * ' + self.B11 + ' ',
                                       self.dir_output_temp, 'GTiff',
                                       E2.extent(), E2.width(), E2.height(),
                                       entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator('"A@1" + "E2@1" * ' + self.B11 + ' ',
                                       self.dir_output, 'GTiff', E2.extent(),
                                       E2.width(), E2.height(), entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 10
0
    def calc_a1(self, dir_output, dir_A, dir_E1, temp_folder, B10):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_A = dir_A
        self.dir_E1 = dir_E1
        self.dir_output_temp = self.path + 'A1.tif'

        self.B10 = B10

        entries = []

        A = QgsRasterLayer(self.dir_A)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'A@1'
        ras.raster = A
        ras.bandNumber = 1
        entries.append(ras)

        E1 = QgsRasterLayer(self.dir_E1)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'E1@1'
        ras.raster = E1
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator('1 + "A@1" + "E1@1" * ' + self.B10,
                                       self.dir_output_temp, 'GTiff',
                                       E1.extent(), E1.width(), E1.height(),
                                       entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator('1 + "A@1" + "E1@1" * ' + self.B10,
                                       self.dir_output, 'GTiff', E1.extent(),
                                       E1.width(), E1.height(), entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 11
0
    def testRasterBlock(self):
        """Test raster block with extent"""

        path = os.path.join(unitTestDataPath(), 'landsat_4326.tif')
        raster_layer = QgsRasterLayer(path, 'test')
        self.assertTrue(raster_layer.isValid())

        extent = QgsRectangle(17.94284482577178252, 30.23021770271909503, 17.94407867909909626, 30.23154272264058307)
        block = raster_layer.dataProvider().block(1, extent, 2, 3)
        self.checkBlockContents(block, [
            125.0, 125.0,
            125.0, 125.0,
            125.0, 124.0,
        ])

        full_content = [
            125.0, 125.0, 125.0,
            125.0, 125.0, 125.0,
            125.0, 124.0, 125.0,
            126.0, 127.0, 127.0,
        ]

        extent = raster_layer.extent()
        block = raster_layer.dataProvider().block(1, extent, 3, 4)
        self.checkBlockContents(block, full_content)

        extent = raster_layer.extent()
        extent.grow(-0.0001)
        block = raster_layer.dataProvider().block(1, extent, 3, 4)
        self.checkBlockContents(block, full_content)

        row_height = raster_layer.extent().height() / raster_layer.height()

        for row in range(raster_layer.height()):
            extent = raster_layer.extent()
            extent.setYMaximum(extent.yMaximum() - row_height * row)
            extent.setYMinimum(extent.yMaximum() - row_height)
            block = raster_layer.dataProvider().block(1, extent, 3, 1)
            self.checkBlockContents(block, full_content[row * 3:row * 3 + 3])
Esempio n. 12
0
    def calc_ndvi(self, dir_output, dir_bred, dir_bnir, temp_folder):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_bred = dir_bred
        self.dir_bnir = dir_bnir
        self.dir_output_temp = self.path + 'NDVI.tif'

        entries = []

        bred = QgsRasterLayer(self.dir_bred)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'bred@1'
        ras.raster = bred
        ras.bandNumber = 1
        entries.append(ras)

        bnir = QgsRasterLayer(self.dir_bnir)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'bnir@1'
        ras.raster = bnir
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator('(bnir@1 - bred@1)/(bnir@1 + bred@1)',
                                       self.dir_output_temp, 'GTiff',
                                       bnir.extent(), bnir.width(),
                                       bnir.height(), entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator(
                '(band5@1 - band4@1)/(band5@1 + band4@1)', self.dir_output,
                'GTiff', bnir.extent(), bnir.width(), bnir.height(), entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 13
0
    def calc_a(self, dir_output, dir_D_10, dir_E0, temp_folder):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_D_10 = dir_D_10
        self.dir_E0 = dir_E0
        self.dir_output_temp = self.path + 'A.tif'

        entries = []

        D_10 = QgsRasterLayer(self.dir_D_10)
        ras = QgsRasterCalculatorEntry()
        ras.ref = '10 - D@1'
        ras.raster = D_10
        ras.bandNumber = 1
        entries.append(ras)

        E0 = QgsRasterLayer(self.dir_E0)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'E0@1'
        ras.raster = E0
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator('"10 - D@1" / "E0@1"',
                                       self.dir_output_temp, 'GTiff',
                                       E0.extent(), E0.width(), E0.height(),
                                       entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator('"10 - D@1" / "E0@1"', self.dir_output,
                                       'GTiff', E0.extent(), E0.width(),
                                       E0.height(), entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 14
0
    def calc_11_bt(self, dir_output, dir_toa_11, temp_folder, val_l_tir2_k1,
                   val_l_tir2_k2):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_toa_11 = dir_toa_11
        self.dir_output_temp = self.path + '11 - BT.tif'

        self.val_l_tir2_k1 = val_l_tir2_k1
        self.val_l_tir2_k2 = val_l_tir2_k2

        entries = []

        toa_11 = QgsRasterLayer(self.dir_toa_11)
        ras = QgsRasterCalculatorEntry()
        ras.ref = '10 - TOA@1'
        ras.raster = toa_11
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator(
                str(self.val_l_tir2_k2) + ' / ln ( ( ' +
                str(self.val_l_tir2_k1) + ' / "10 - TOA@1" ) + 1) ',
                self.dir_output_temp, 'GTiff', toa_11.extent(), toa_11.width(),
                toa_11.height(), entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator(
                str(self.val_l_tir2_k2) + ' / ln ( ( ' +
                str(self.val_l_tir2_k1) + ' / "10 - TOA@1" ) + 1) ',
                self.dir_output, 'GTiff', toa_11.extent(), toa_11.width(),
                toa_11.height(), entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 15
0
def pngs(file):
    image_name = pathlib.Path(file).name.split('.')[0]
    #add vectorlayers
    qgis_init()
    project = QgsProject.instance()
    # project_name = PATH+'/'+image_name+'.qgz'
    # project.write(project_name)

    rlayer = QgsRasterLayer(file, image_name)
    # QgsProject.instance().addMapLayer(rlayer, False)
    project.addMapLayer(rlayer, False)
    # project.write(project_name)
    layer = project.mapLayersByName(image_name)[0]

    settings = QgsMapSettings()
    settings.setLayers([layer])
    settings.setBackgroundColor(QColor(255, 255, 255))

    # max_height = vres
    width = rlayer.width()
    height = rlayer.height()

    # if height < max_height:
    #     new_height=2048
    #     new_width = round(width*new_height/height)

    # else:
    new_height = vres
    new_width = int(width * new_height / height)

    # new_width = (layer.width()/res)
    # new_height = int(layer.height()/res)
    settings.setOutputSize(QSize(new_width, new_height))
    settings.setExtent(layer.extent())

    render = QgsMapRendererSequentialJob(settings)

    def finished():
        img = render.renderedImage()
        # save the image; e.g. img.save("/Users/myuser/render.png","png")
        name = PATH + '/PNGs/' + image_name + '_print.png'
        img.save(name, "png")

    render.finished.connect(finished)
    render.start()
    render.waitForFinished()
    # print('rendering: ', image_name)
    # print(QgsProject.instance().mapLayers())
    project.clear()
    def replaceImage(self, filepath, title):
        self.title = title
        self.filepath = filepath

         # set custom properties
        self.setCustomProperty("title", title)
        self.setCustomProperty("filepath", self.filepath)
        self.setName(title)

        fileInfo = QFileInfo(filepath)
        ext = fileInfo.suffix()
        if ext == "pdf":
            s = QSettings()
            oldValidation = s.value("/Projections/defaultBehavior")
            s.setValue("/Projections/defaultBehavior", "useGlobal")  # for not asking about crs
            path = fileInfo.filePath()
            baseName = fileInfo.baseName()
            layer = QgsRasterLayer(path, baseName)
            self.image = layer.previewAsImage(QSize(layer.width(), layer.height()))
            s.setValue("/Projections/defaultBehavior", oldValidation)
        else:
            reader = QImageReader(filepath)
            self.image = reader.read()
        self.repaint()
Esempio n. 17
0
    def calc_11_bt_L7(self):
        dir_output = self.dlg.fw_output.filePath()
        output_toa_11 = str(
            Path(dir_output).parent) + '\\temp_folder\\11 - TOA.tif'
        output_bt_11 = str(
            Path(dir_output).parent) + '\\temp_folder\\11 - BT.tif'

        entries = []

        toa_11 = QgsRasterLayer(output_toa_11)
        ras = QgsRasterCalculatorEntry()
        ras.ref = '10 - TOA@1'
        ras.raster = toa_11
        ras.bandNumber = 1
        entries.append(ras)

        if os.path.exists(Path(dir_output).parent):
            calc = QgsRasterCalculator(
                str(L_TIR2_K2_L7) + ' / ln ( ( ' + str(L_TIR2_K1_L7) +
                ' / "10 - TOA@1" ) + 1) ', output_bt_11, 'GTiff',
                toa_11.extent(), toa_11.width(), toa_11.height(), entries)
            calc.processCalculation()
        else:
            print("else")
Esempio n. 18
0
    def ProcessNBR(self, inFileA, inFileB):
        msg = u"NBR Processing for " + self.sceneID + "..."
        iface.mainWindow().statusBar().showMessage(msg)
        QgsMessageLog.logMessage(msg, level=QgsMessageLog.INFO)
        try:
            calculatorEntryList = []
            tempOutFile = self.outFileNBR.replace("NBR", "NBR_temp")

            fileInfo1 = QFileInfo(inFileA)
            baseName1 = fileInfo1.baseName()
            newLayer1 = QgsRasterLayer(inFileA, baseName1)
            boh1 = QgsRasterCalculatorEntry()
            boh1.ref = "boh@1"
            boh1.bandNumber = 1
            calculatorEntryList.append(boh1)
            boh1.raster = newLayer1

            if newLayer1.isValid():
                extents = newLayer1.extent()
                colCt = newLayer1.width()
                rowCt = newLayer1.height()
            else:
                raise IOError(u"Error, Invalid layer read!")

            fileInfo2 = QFileInfo(inFileB)
            baseName2 = fileInfo2.baseName()
            newLayer2 = QgsRasterLayer(inFileB, baseName2)
            boh2 = QgsRasterCalculatorEntry()
            boh2.ref = "boh@2"
            boh2.bandNumber = 1
            calculatorEntryList.append(boh2)
            boh2.raster = newLayer2
            if not newLayer2.isValid():
                raise IOError(u"Error, Invalid layer read!")

            formula = ("(((boh@1 != 0 AND boh@2 != 0) * "
                       "(boh@1 - boh@2) / (boh@1 + boh@2) * 1000) + "
                       "((boh@1 = 0 OR boh@2 = 0) * " + str(self.minShort) +
                       "))")

            # Process calculation with input extent and resolution
            calc = QgsRasterCalculator(formula, tempOutFile, 'GTiff', extents,
                                       colCt, rowCt, calculatorEntryList)

            result = calc.processCalculation()

            if result != 0:
                raise RuntimeError(u"Raster calculator failed.")

            # convert Raster Calculator result to int 16
            self.Float2IntTif(tempOutFile, self.outFileNBR)
        except:
            raise RuntimeError(u"Unspecified error when calculating NBR")
        finally:
            # cleanup
            calculatorEntryList = None
            fileInfo1 = None
            baseName1 = None
            fileInfo2 = None
            baseName2 = None
            formula = None
            boh1 = None
            boh2 = None
            calc = None
            newLayer1 = None
            newLayer2 = None

            del calculatorEntryList
            del fileInfo1
            del baseName1
            del fileInfo2
            del baseName2
            del formula
            del boh1
            del boh2
            del calc
            del newLayer1
            del newLayer2
        gc.collect()

        msg = u"NBR Processing for " + self.sceneID + " Completed"
        iface.mainWindow().statusBar().showMessage(msg)
        QgsMessageLog.logMessage(msg, level=QgsMessageLog.INFO)
        iface.mainWindow().statusBar().showMessage("")
        return result
    def initializeLayer(self, screenExtent=None):
        if self.error or self.initialized or self.initializing:
            return

        if self.filepath is not None:
            # not safe...
            self.initializing = True
            filepath = self.getAbsoluteFilepath()

            if not os.path.exists(filepath):
                # TODO integrate with BadLayerHandler ?
                loadErrorDialog = LoadErrorDialog(filepath)
                result = loadErrorDialog.exec_()
                if result == 1:
                    # absolute
                    filepath = loadErrorDialog.lineEditImagePath.text()
                    # to relative if needed
                    self.filepath = utils.toRelativeToQGS(filepath)
                    self.setCustomProperty("filepath", self.filepath)
                    QgsProject.instance().setDirty(True)
                else:
                    self.error = True

                del loadErrorDialog

            fileInfo = QFileInfo(filepath)
            ext = fileInfo.suffix()
            if ext == "pdf":
                s = QSettings()
                oldValidation = s.value("/Projections/defaultBehavior")
                s.setValue("/Projections/defaultBehavior", "useGlobal") # for not asking about crs
                path = fileInfo.filePath()
                baseName = fileInfo.baseName()
                layer = QgsRasterLayer(path, baseName)
                self.image = layer.previewAsImage(QSize(layer.width(),layer.height()))
                s.setValue("/Projections/defaultBehavior", oldValidation)
            else:
                reader = QImageReader(filepath)
                self.image = reader.read()

            self.initialized = True
            self.initializing = False

            self.setupCrs()

            if screenExtent:
                # constructor called from AddLayer action
                # if not, layer loaded from QGS project file

                # check if image already has georef info
                # use GDAL
                dataset = gdal.Open(filepath, gdal.GA_ReadOnly)
                georef = None
                if dataset:
                    georef = dataset.GetGeoTransform()

                if georef and not self.is_default_geotransform(georef):
                    self.initializeExistingGeoreferencing(dataset, georef)
                else:
                    # init to default params
                    self.setCenter(screenExtent.center())
                    self.setRotation(0.0)

                    sw = screenExtent.width()
                    sh = screenExtent.height()

                    self.resetScale(sw, sh)

                    self.commitTransformParameters()
    def initializeLayer(self, screenExtent=None):
        if self.error or self.initialized or self.initializing:
            return

        if self.filepath is not None:
            # not safe...
            self.initializing = True
            absPath = self.getAbsoluteFilepath()

            if not os.path.exists(absPath):
                # TODO integrate with BadLayerHandler ?
                loadErrorDialog = LoadErrorDialog(absPath)
                result = loadErrorDialog.exec_()
                if result == 1:
                    # absolute
                    absPath = loadErrorDialog.lineEditImagePath.text()
                    # to relative if needed
                    self.filepath = utils.toRelativeToQGS(absPath)
                    self.setCustomProperty("filepath", self.filepath)
                    QgsProject.instance().setDirty(True)
                else:
                    self.error = True

                del loadErrorDialog

            imageFormat = utils.imageFormat(absPath)
            if imageFormat == "pdf":
                s = QSettings()
                oldValidation = s.value("/Projections/defaultBehavior")
                s.setValue(
                    "/Projections/defaultBehavior", "useGlobal"
                )  # for not asking about crs
                layer = QgsRasterLayer(absPath, os.path.basename(absPath))
                self.image = layer.previewAsImage(QSize(layer.width(), layer.height()))
                s.setValue("/Projections/defaultBehavior", oldValidation)
            else:
                has_corrected = False
                if imageFormat == "tif":
                    # other than TIFF => assumes can be loaded by Qt
                    has_corrected = self.preCheckImage(absPath)
                if has_corrected:
                    # image already loaded by preCheckImage
                    self.showBarMessage(
                        "Raster changed",
                        "Raster content has been transformed for display in the "
                        "plugin. "
                        "When exporting, select the 'Only export world file' checkbox.",
                        Qgis.Warning,
                        10,
                    )
                else:
                    reader = QImageReader(absPath)
                    self.image = reader.read()

            self.initialized = True
            self.initializing = False

            self.setupCrs()

            if screenExtent:
                # constructor called from AddLayer action
                # if not, layer loaded from QGS project file

                # check if image already has georef info
                # use GDAL
                dataset = gdal.Open(absPath, gdal.GA_ReadOnly)
                georef = None
                if dataset:
                    georef = dataset.GetGeoTransform()

                if georef and not self.is_default_geotransform(georef):
                    self.initializeExistingGeoreferencing(dataset, georef)
                else:
                    # init to default params
                    self.setCenter(screenExtent.center())
                    self.setRotation(0.0)

                    sw = screenExtent.width()
                    sh = screenExtent.height()

                    self.resetScale(sw, sh)

                    self.commitTransformParameters()
Esempio n. 21
0
def mapa_final_no_compensatorio(n_variables, pesos, raster_inputs,
                                raster_salida):

    ecuacion = '('
    for a, b in zip(range(n_variables), pesos):

        if a < n_variables - 1:
            ecuacion += ("(" + str(b) + "^10) * " + "'(1 - (layer" +
                         str(a + 1) + "@1 ^10))'" + ' + ')
        else:
            ecuacion += ("(" + str(b) + "^10) * " + "'(1 - (layer" +
                         str(a + 1) + "@1 ^10))'")
    ecuacion += '  ) ^ 1/10'
    entries = []

    #abre el archivo raster1
    fileInfo = QFileInfo(raster_inputs[0])
    path = fileInfo.filePath()
    baseName = fileInfo.baseName()
    layer1 = QgsRasterLayer(path, baseName)
    var1 = QgsRasterCalculatorEntry()
    var1.ref = 'layer1@1'
    var1.raster = layer1
    var1.bandNumber = 1
    entries.append(var1)

    if n_variables == 2:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)
    elif n_variables == 3:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)

        fileInfo = QFileInfo(raster_inputs[2])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer3 = QgsRasterLayer(path, baseName)
        var3 = QgsRasterCalculatorEntry()
        var3.ref = 'layer3@1'
        var3.raster = layer3
        var3.bandNumber = 1
        entries.append(var3)

    elif n_variables == 4:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)

        fileInfo = QFileInfo(raster_inputs[2])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer3 = QgsRasterLayer(path, baseName)
        var3 = QgsRasterCalculatorEntry()
        var3.ref = 'layer3@1'
        var3.raster = layer3
        var3.bandNumber = 1
        entries.append(var3)

        fileInfo = QFileInfo(raster_inputs[3])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer4 = QgsRasterLayer(path, baseName)
        var4 = QgsRasterCalculatorEntry()
        var4.ref = 'layer4@1'
        var4.raster = layer4
        var4.bandNumber = 1
        entries.append(var4)

    elif n_variables == 5:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)

        fileInfo = QFileInfo(raster_inputs[2])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer3 = QgsRasterLayer(path, baseName)
        var3 = QgsRasterCalculatorEntry()
        var3.ref = 'layer3@1'
        var3.raster = layer3
        var3.bandNumber = 1
        entries.append(var3)

        fileInfo = QFileInfo(raster_inputs[3])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer4 = QgsRasterLayer(path, baseName)
        var4 = QgsRasterCalculatorEntry()
        var4.ref = 'layer4@1'
        var4.raster = layer4
        var4.bandNumber = 1
        entries.append(var4)

        fileInfo = QFileInfo(raster_inputs[4])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer5 = QgsRasterLayer(path, baseName)
        var5 = QgsRasterCalculatorEntry()
        var5.ref = 'layer5@1'
        var5.raster = layer5
        var5.bandNumber = 1
        entries.append(var5)

    calc = QgsRasterCalculator(ecuacion, raster_salida,
                               'GTiff', layer1.extent(), layer1.width(),
                               layer1.height(), entries)

    calc.processCalculation()
Esempio n. 22
0
def raster_calc_qgis(ecuacion, raster_inputs, raster_salida):
    n_variables = len(raster_inputs)

    entries = []

    #abre el archivo raster1
    fileInfo = QFileInfo(raster_inputs[0])
    path = fileInfo.filePath()
    baseName = fileInfo.baseName()
    layer1 = QgsRasterLayer(path, baseName)
    var1 = QgsRasterCalculatorEntry()
    var1.ref = 'layer1@1'
    var1.raster = layer1
    var1.bandNumber = 1
    entries.append(var1)

    if n_variables == 2:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)
    elif n_variables == 3:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)

        fileInfo = QFileInfo(raster_inputs[2])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer3 = QgsRasterLayer(path, baseName)
        var3 = QgsRasterCalculatorEntry()
        var3.ref = 'layer3@1'
        var3.raster = layer3
        var3.bandNumber = 1
        entries.append(var3)

    elif n_variables == 4:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)

        fileInfo = QFileInfo(raster_inputs[2])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer3 = QgsRasterLayer(path, baseName)
        var3 = QgsRasterCalculatorEntry()
        var3.ref = 'layer3@1'
        var3.raster = layer3
        var3.bandNumber = 1
        entries.append(var3)

        fileInfo = QFileInfo(raster_inputs[3])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer4 = QgsRasterLayer(path, baseName)
        var4 = QgsRasterCalculatorEntry()
        var4.ref = 'layer4@1'
        var4.raster = layer4
        var4.bandNumber = 1
        entries.append(var4)

    elif n_variables == 5:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)

        fileInfo = QFileInfo(raster_inputs[2])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer3 = QgsRasterLayer(path, baseName)
        var3 = QgsRasterCalculatorEntry()
        var3.ref = 'layer3@1'
        var3.raster = layer3
        var3.bandNumber = 1
        entries.append(var3)

        fileInfo = QFileInfo(raster_inputs[3])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer4 = QgsRasterLayer(path, baseName)
        var4 = QgsRasterCalculatorEntry()
        var4.ref = 'layer4@1'
        var4.raster = layer4
        var4.bandNumber = 1
        entries.append(var4)

        fileInfo = QFileInfo(raster_inputs[4])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer5 = QgsRasterLayer(path, baseName)
        var5 = QgsRasterCalculatorEntry()
        var5.ref = 'layer5@1'
        var5.raster = layer5
        var5.bandNumber = 1
        entries.append(var5)

    calc = QgsRasterCalculator(ecuacion, raster_salida,
                               'GTiff', layer1.extent(), layer1.width(),
                               layer1.height(), entries)

    calc.processCalculation()
    def run(self):
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            """read path from user input"""
            inputPath = self.dlg.Path.text()
            """set path for output file and concat file name to path"""
            outputPath = 'C:\Users\Administrator\Desktop\\'
            outputName = self.dlg.fileName.text()
            outputFile = outputPath + outputName
             
            """read image and calculate electrical conductivity and electrical Resistivity and set RGB for each pixel which R represent adj Pred Moist,
            G represents electrical conductivity and B represents electrical resistivity"""
            """for tiff file output"""
            if(self.dlg.tiff.isChecked()):
                oldImage = Image.open(inputPath)
                rgb_image = oldImage.convert('RGB')
                newImage = Image.new(oldImage.mode,oldImage.size,'white')
                for x in xrange(newImage.size[0]):
                    for y in xrange(newImage.size[1]):
                        R, G, B = rgb_image.getpixel((x, y))
                        sand = (R * 0.4 / 255.0)
                        clay = (G * 0.5 / 255.0)
                        om = (B * 5 / 255.0)
                        predMoist = -0.251 * sand + 0.195 * clay + 0.011 * om + 0.006 * sand * om - 0.027 * clay * om + 0.452 * sand * clay + 0.299
                        adjPredMoist = predMoist + (1.283 * predMoist * predMoist - 0.374 * predMoist - 0.015)
                        electricalConductivity = 0.000471052 * math.pow(100 * adjPredMoist, 3.458)
                        electricalResistivity = 1000.0 / electricalConductivity
                        newImage.putpixel((x,y),(int(adjPredMoist), int(electricalConductivity), int(electricalResistivity)))
                newImage.save(outputFile + '.tif')
            
            """create raster layer and calculate electrical conductivity and write in ASCII XYZ file which X and Y represent centroid coordinate of each pixel
            and Z represents electrical conductivity"""
            """for ASCII XYZ file output"""
            if(self.dlg.asciiXYZ.isChecked()):
                raster = QgsRasterLayer(inputPath)
                w = raster.width()
                h = raster.height()
                p = raster.dataProvider()
                b = p.block(0, p.extent(), w, h)
                f = file(outputFile + '.xyz', 'w')
                f.write('X,Y,Z(Electrical Conductivity)\n')
                pix_x = raster.rasterUnitsPerPixelX()
                pix_y = raster.rasterUnitsPerPixelY()
                half_x = pix_x / 2
                half_y = pix_y / 2
			
                extent = p.extent()
			
                count = 0
                y = extent.yMinimum()
                while y < extent.yMaximum():
                    y += pix_y
                    count += 1
                    x = extent.xMinimum()
                    while x < extent.xMaximum():
                        x += pix_x
                        pos = QgsPoint(x - half_x, y - half_y)
                        R = p.identify(pos, QgsRaster.IdentifyFormatValue).results()[1]
                        G = p.identify(pos, QgsRaster.IdentifyFormatValue).results()[2]
                        B = p.identify(pos, QgsRaster.IdentifyFormatValue).results()[3]
                        sand = (R * 0.4 / 255.0)
                        clay = (G * 0.5 / 255.0)
                        om = (B * 5 / 255.0)
                        predMoist = -0.251 * sand + 0.195 * clay + 0.011 * om + 0.006 * sand * om - 0.027 * clay * om + 0.452 * sand * clay + 0.299
                        adjPredMoist = predMoist + (1.283 * predMoist * predMoist - 0.374 * predMoist - 0.015)
                        electricalConductivity = 0.000471052 * math.pow(100 * adjPredMoist, 3.458)
                        f.write('%s, %s, %s\n' % (pos.x(),pos.y(), electricalConductivity))
                f.close()
Esempio n. 24
0
def readRasterLayer(i, allBandData):
    # pylint: disable=too-many-locals

    fileInfo = QFileInfo(shared.rasterFileName[i])
    fileBaseName = fileInfo.baseName()

    layer = QgsRasterLayer(shared.rasterFileName[i], fileBaseName)
    if not layer.isValid():
        shared.fpOut.write("Raster layer '" + shared.rasterFileName[i] +
                           "'failed to load")
        return -1

    # Store the title as the first list item
    allBandData.append(shared.rasterFileTitle[i])

    # Get more info
    xSize = layer.width()
    ySize = layer.height()

    cellWidth = layer.rasterUnitsPerPixelX()
    cellHeight = layer.rasterUnitsPerPixelY()

    provider = layer.dataProvider()
    extnt = provider.extent()
    dpi = provider.dpi()

    shared.fpOut.write("Raster layer '" + shared.rasterFileTitle[i] +
                       "' loaded with X, Y resolution = " + str(cellWidth) +
                       ", " + str(cellHeight) + " m\n")
    #shared.fpOut.write(layer.metadata())
    #shared.fpOut.write(layer.rasterType())

    # Store the above as the second list item
    allBandData.append(
        [provider, xSize, ySize, cellWidth, cellHeight, extnt, dpi])

    # Now store the data for each band as a QgsRasterBlock
    nBands = layer.bandCount()
    for band in range(nBands):
        #shared.fpOut.write(layer.bandName(i))

        bandData = provider.block(band, extnt, xSize, ySize)

        # Store as a further list item
        allBandData.append(bandData)

    # Sort out style
    #shared.fpOut.write("Style file " + str(i) + " is " + shared.rasterFileStyle[i])
    if not shared.rasterFileStyle[i]:
        # No style file specified, so try the default style for this layer
        shared.rasterFileStyle[i] = layer.styleURI()
        #shared.fpOut.write("Trying default style file " + shared.rasterFileStyle[i])

        if not layer.loadDefaultStyle():
            shared.fpOut.write("Could not load default style '" +
                               shared.rasterFileStyle[i] +
                               "' for raster layer '" +
                               shared.rasterFileTitle[i] + "'")

    else:
        # A style file was specified, so try to load it
        #shared.fpOut.write("Trying style file " + shared.rasterFileStyle[i])
        if not layer.loadNamedStyle(shared.rasterFileStyle[i]):
            shared.fpOut.write("Could not load style '" +
                               shared.rasterFileStyle[i] +
                               "' for raster layer '" +
                               shared.rasterFileTitle[i] + "'")

    # Set opacity
    layer.renderer().setOpacity(shared.rasterFileOpacity[i])

    # Add this layer to the app's registry
    QgsProject.instance().addMapLayer(layer)

    return layer
    def processAlgorithm(self, parameters, context, model_feedback):
        results = {}
        outputs = {}
        inputrasters = []
        feedback = QgsProcessingMultiStepFeedback(1, model_feedback)
        filenamepattern = re.compile(parameters['FILENAMEMASK'])
        height = None
        width = None
        for raster in parameters['INPUT']:
            feedback.pushDebugInfo("layer: " + str(raster))
            match = filenamepattern.match(raster)
            if not match:
                layers = QgsProject.instance().mapLayersByName(raster[:13])
                if not layers:
                    continue
                layer = layers[0]
                filename = layer.dataProvider().dataSourceUri()
                match = filenamepattern.match(filename)
                if not match:
                    continue
            else:
                filename = raster
                layer = QgsRasterLayer(filename, match.group(1), "gdal")
                if not layer.isValid():
                    continue
            feedback.pushDebugInfo("size: " + str(layer.height()) + "x" +
                                   str(layer.width()))
            if height is None:
                height = layer.height()
            if width is None:
                width = layer.width()
            if layer.height() != height:
                continue
            if layer.width() != width:
                continue

            date = datetime.strptime(match.group(2), parameters['DATEFORMAT'])
            inputrasters.append({'date': date, 'filename': filename})
        feedback = QgsProcessingMultiStepFeedback(len(inputrasters),
                                                  model_feedback)

        def get_date(e):
            return e.get('date')

        inputrasters.sort(key=get_date)
        feedback.pushDebugInfo("inputrasters: " + str(inputrasters))
        previnput = None
        sumraster = None
        i = 0
        for inputraster in inputrasters:
            if previnput is None:
                previnput = inputraster
                if sumraster is None:
                    sumraster = self.nullraster(inputraster['filename'],
                                                parameters['OUTPUT'], context,
                                                feedback)['OUTPUT']
                continue
            delta = inputraster['date'] - previnput['date']
            outputs['CalcDaysOverLimit'] = self.adddaysoverthreshold(
                sumraster, previnput['filename'], inputraster['filename'],
                delta.days, parameters['THRESHOLD'], context, feedback)
            sumraster = outputs['CalcDaysOverLimit']['OUTPUT']
            previnput = inputraster
            i = i + 1
            feedback.setCurrentStep(i)
            if feedback.isCanceled():
                return {}
        results['OUTPUT'] = outputs['CalcDaysOverLimit']['OUTPUT']

        return results
Esempio n. 26
0
        dataOut = tempfile.mktemp('.tif')
    except Exception, e:
        raise Exception(
            'Problem creating temporary file to store raster data: ' + str(e))
    # TODO: Work out if the response is an XML error
    update.emit({'progress': 10, 'message': 'Downloading file...'})

    urllib.urlretrieve(bigURL, dataOut)

    # Load data as QgsRasterLayer and then re-save it, ensuring it has the correct projection info
    a = QgsRasterLayer(dataOut, "temporary raster layer")
    # Double-confirm projection info (sometimes WCS has it in the meta but not the file)
    crs = a.crs()
    crs.createFromId(int(srs.split(':')[1]))
    a.setCrs(crs)
    update.emit({'progress': 90, 'message': 'Saving file...'})
    writer = QgsRasterFileWriter(output_file)

    pipe = QgsRasterPipe()
    width, height = a.width(), a.height()
    extent = a.extent()
    provider = a.dataProvider()
    pipe.set(provider.clone())
    writer.writeRaster(pipe, width, height, extent, a.crs())
    a = None
    pipe = None
    provider = None
    # Delete temp file
    os.remove(dataOut)
    return output_file
Esempio n. 27
0
    def processAlgorithm(self, parameters, context, feedback):
        self.parameters = parameters
        self.context = context
        self.feedback = feedback
        load_geotiffs = self.parameterAsInt(parameters, self.PrmLoadGeoTiffs,
                                            context)
        out_folder = self.parameterAsFile(parameters,
                                          self.PrmGroundOverlayFolder, context)
        input_file = self.parameterAsFile(parameters, self.PrmInput, context)
        f, extension = os.path.splitext(input_file)
        dirname = os.path.dirname(input_file)
        extension = extension.lower()
        try:
            if extension == '.kmz':
                kmz = ZipFile(input_file, 'r')
                kml = kmz.open('doc.kml', 'r')
            elif extension == '.kml':
                kml = open(input_file,
                           encoding="utf-8",
                           errors="backslashreplace")
            else:
                msg = "Invalid extension: Should be kml or kmz"
                raise QgsProcessingException(msg)
        except Exception:
            msg = "Failed to open file"
            raise QgsProcessingException(msg)

        parser = xml.sax.make_parser()

        self.overlays = []
        # Set up the handler for doing the main processing
        handler = GroundOverlayHandler(feedback)
        handler.groundoverlay.connect(self.groundoverlay)
        parser.setContentHandler(handler)
        try:
            input_source = xml.sax.xmlreader.InputSource()
            input_source.setByteStream(kml)
            input_source.setEncoding('utf-8')
            parser.parse(input_source)
        except Exception:
            '''s = traceback.format_exc()
            feedback.pushInfo(s)'''
            feedback.reportError(
                tr('Failure in kml extraction - May return partial results.'))
            handler.endDocument()

        # Iterate through each found overlay images
        for overlay in self.overlays:
            north = overlay[0]
            south = overlay[1]
            east = overlay[2]
            west = overlay[3]
            rotation = overlay[4]
            href = overlay[5]
            if href.startswith('http:') or href.startswith('https:'):
                feedback.reportError(
                    'Cannot process network images: {}'.format(href))
                continue
            if extension == '.kmz':
                try:
                    image = kmz.read(href)
                    output_file = os.path.basename(href)
                    file_name, ext = os.path.splitext(output_file)
                    # Write out a temporary image
                    temp_file_name = os.path.join(
                        out_folder, '{}_temp{}'.format(file_name, ext))
                    fp = open(temp_file_name, "wb")
                    fp.write(image)
                    fp.close()
                    raster = QgsRasterLayer(temp_file_name, "temp")
                except Exception:
                    feedback.reportError(
                        'Image does not exist: {}'.format(href))
                    continue
            else:
                # Check to see if it is a valid file name
                in_path = os.path.join(dirname, href)
                if not os.path.isfile(in_path):
                    # The path was not valid
                    feedback.reportError(
                        'Image file does not exist: {}'.format(in_path))
                    continue
                raster = QgsRasterLayer(in_path, "temp")
                output_file = os.path.basename(in_path)
                file_name, ext = os.path.splitext(output_file)
            if not raster.isValid():
                feedback.reportError('Invalid raster image: {}'.format(href))
                continue
            out_path = os.path.join(out_folder, file_name + ".tif")
            if rotation == 0:
                status = processing.run(
                    "gdal:translate", {
                        'INPUT':
                        raster,
                        'EXTRA':
                        '-a_srs EPSG:4326 -a_ullr {} {} {} {}'.format(
                            west, north, east, south),
                        'DATA_TYPE':
                        0,
                        'OUTPUT':
                        out_path
                    })
            else:
                rwidth = raster.width()
                rheight = raster.height()
                center_x = (east + west) / 2.0
                center_y = (north + south) / 2.0
                center_pt = QgsPointXY(center_x, center_y)
                ul_pt = QgsPointXY(west, north)
                ur_pt = QgsPointXY(east, north)
                lr_pt = QgsPointXY(east, south)
                ll_pt = QgsPointXY(west, south)
                distance = center_pt.distance(ul_pt)
                az = center_pt.azimuth(ul_pt) - rotation
                pt1 = center_pt.project(distance, az)
                az = center_pt.azimuth(ur_pt) - rotation
                pt2 = center_pt.project(distance, az)
                az = center_pt.azimuth(lr_pt) - rotation
                pt3 = center_pt.project(distance, az)
                az = center_pt.azimuth(ll_pt) - rotation
                pt4 = center_pt.project(distance, az)
                gcp1 = '-gcp {} {} {} {}'.format(0, 0, pt1.x(), pt1.y())
                gcp2 = '-gcp {} {} {} {}'.format(rwidth, 0, pt2.x(), pt2.y())
                gcp3 = '-gcp {} {} {} {}'.format(rwidth, rheight, pt3.x(),
                                                 pt3.y())
                gcp4 = '-gcp {} {} {} {}'.format(0, rheight, pt4.x(), pt4.y())

                status = processing.run(
                    "gdal:translate", {
                        'INPUT':
                        raster,
                        'EXTRA':
                        '-a_srs EPSG:4326 -a_nodata 0,0,0 {} {} {} {}'.format(
                            gcp1, gcp2, gcp3, gcp4),
                        'DATA_TYPE':
                        0,
                        'OUTPUT':
                        out_path
                    })
            if load_geotiffs:
                context.addLayerToLoadOnCompletion(
                    out_path,
                    context.LayerDetails(file_name, project=context.project()))

            del raster
            if extension == '.kmz':
                try:
                    os.remove(temp_file_name)
                    os.remove(temp_file_name + '.aux.xml')
                except Exception:
                    pass

        if extension == '.kmz':
            kmz.close()
        else:
            kml.close()

        # self.feedback.pushInfo('Number of overlays: {}'.format(len(self.overlays)))

        return ({})
Esempio n. 28
0
    def run(self):
        """Run method that performs all the real work"""
        # Add items to Management Practices & Soil Type
        k_lists = []
        m_lists = []

        k_lists = self.k_list()
        m_lists = self.m_list()

        self.dlg.comboBox.addItems(k_lists)
        self.dlg.comboBox_2.addItems(m_lists)

        # show dialog box
        self.dlg.show()

        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:

            # Save paths of input directories
            selectedBoundary = self.dlg.lineEdit.text()
            selectedDEM = self.dlg.lineEdit_2.text()
            selectedRLayer = self.dlg.lineEdit_3.text()

            selectedOutput = self.dlg.lineEdit_4.text()
            for letter in selectedOutput:
                if letter == "\\":
                    selectedOutput = selectedOutput.replace(letter, "/")

            print(selectedBoundary)
            print(selectedDEM)
            print(selectedRLayer)
            print(selectedOutput)

            # Save indices for K and M
            selectedKLayer = self.dlg.comboBox.currentIndex()
            selectedMLayer = self.dlg.comboBox_2.currentIndex()

            boundary = QgsVectorLayer(selectedBoundary, 'Boundary', 'ogr')
            QgsMapLayerRegistry.instance().addMapLayer(boundary)

            entries = []

            # Retrieve K and M values

            k_value = self.k_index(selectedKLayer)
            m_value = self.m_index(selectedMLayer)

            km_value = k_value * m_value
            km_value = str(km_value)

            # Process R index

            ## CSV to Layer
            uri = 'file:///' + selectedRLayer + '?delimiter=%s&xField=%s&yField=%s&crs=%s' % (
                ",", "x", "y", "EPSG:4326")
            rainfall_unedited = QgsVectorLayer(uri, "rainfall",
                                               "delimitedtext")
            QgsMapLayerRegistry.instance().addMapLayer(rainfall_unedited)
            spatRef = QgsCoordinateReferenceSystem(
                4326, QgsCoordinateReferenceSystem.EpsgCrsId)

            ## CSV points to editable shapefile
            rainfall_edited = QgsVectorFileWriter(
                selectedOutput + '/rainfall_edited.shp', None,
                rainfall_unedited.pendingFields(), QGis.WKBPoint, spatRef)

            pt = QgsPoint()
            outFeature = QgsFeature()

            for feat in rainfall_unedited.getFeatures():
                attrs = feat.attributes()
                pt.setX(feat['x'])
                pt.setY(feat['y'])
                outFeature.setAttributes(attrs)
                outFeature.setGeometry(QgsGeometry.fromPoint(pt))
                rainfall_edited.addFeature(outFeature)
            del rainfall_edited

            rainfall_edited2 = QgsVectorLayer(
                selectedOutput + '/rainfall_edited.shp', 'rainfall_edited',
                'ogr')

            ## Add and calculate average field
            rainfall_edited2.startEditing()

            avgField = QgsField('average', QVariant.Double)
            rainfall_edited2.dataProvider().addAttributes([avgField])
            rainfall_edited2.updateFields()
            idx = rainfall_edited2.fieldNameIndex('average')

            time_count = idx - 2
            str_output = ''
            for i in range(1, time_count + 1):
                if i == 1:
                    a = str(i)
                    str_output += 'time' + a

                else:
                    a = str(i)
                    str_output += '+ time' + a

            e = QgsExpression(str_output)
            e.prepare(rainfall_edited2.pendingFields())

            for f in rainfall_edited2.getFeatures():
                f[idx] = e.evaluate(f) / time_count
                rainfall_edited2.updateFeature(f)

            rainfall_edited2.commitChanges()

            rainfall_edited3 = QgsVectorLayer(
                selectedOutput + '/rainfall_edited.shp', 'rainfall_edited',
                'ogr')
            QgsMapLayerRegistry.instance().addMapLayer(rainfall_edited3)

            ## Interpolating average using IDW
            ### Parameters for interpolation
            idx = rainfall_edited3.fieldNameIndex('average')

            layer_data = qgis.analysis.QgsInterpolator.LayerData()
            layer_data.vectorLayer = rainfall_edited3
            layer_data.zCoordInterpolation = False
            layer_data.interpolationAttribute = idx
            layer_data.mInputType = 1

            idw_interpolator = QgsIDWInterpolator([layer_data])

            ### Output parameter
            export_path = selectedOutput + "/interpolated_r_{}.asc".format(idx)
            rect = boundary.extent()
            res = 0.0001
            ncol = (rect.xMaximum() - rect.xMinimum()) / res
            nrows = (rect.yMaximum() - rect.yMinimum()) / res

            interpolated_r = QgsGridFileWriter(idw_interpolator,
                                               export_path, rect, int(ncol),
                                               int(nrows), res, res)
            interpolated_r.writeFile(True)

            interpolated_r2 = QgsRasterLayer(export_path, "interpolated_r")

            ## Clip output to boundary
            clippedR = processing.runandload(
                'gdalogr:cliprasterbymasklayer',
                interpolated_r2,  #INPUT <ParameterRaster>
                boundary,  #MASK <ParameterVector>
                "-9999",  #NO_DATA <ParameterString>
                False,  #ALPHA_BAND <ParameterBoolean>
                False,  #CROP_TO_CUTLINE <ParameterBoolean>
                False,  #KEEP_RESOLUTION <ParameterBoolean>
                5,  #RTYPE <ParameterSelection>
                4,  #COMPRESS <ParameterSelection>
                1,  #JPEGCOMPRESSION <ParameterNumber>
                6,  #ZLEVEL <ParameterNumber>
                1,  #PREDICTOR <ParameterNumber>
                False,  #TILED <ParameterBoolean>
                2,  #BIGTIFF <ParameterSelection>
                False,  #TFW <ParameterBoolean>
                "",  #EXTRA <ParameterString>
                selectedOutput +
                '/clip_interpolated_r.tif')  #OUTPUT <OutputRaster>

            r_layer = QgsRasterLayer(
                selectedOutput + '/clip_interpolated_r.tif', "R-index")
            boh4 = QgsRasterCalculatorEntry()
            boh4.ref = 'boh4@1'
            boh4.raster = r_layer
            boh4.bandNumber = 1
            entries.append(boh4)

            # Process S index
            ## Load DEM

            bohLayer1 = QgsRasterLayer(selectedDEM, "DEM")
            boh2 = QgsRasterCalculatorEntry()
            boh2.ref = 'boh2@1'
            boh2.raster = bohLayer1
            boh2.bandNumber = 1
            entries.append(boh2)

            ## Clip output to boundary
            clippedOutput2 = processing.runandload(
                'gdalogr:cliprasterbymasklayer',
                bohLayer1,  # INPUT <ParameterRaster>
                boundary,  # MASK <ParameterVector>
                "-9999",  # NO_DATA <ParameterString>
                False,  # ALPHA_BAND <ParameterBoolean>
                False,  # CROP_TO_CUTLINE <ParameterBoolean>
                False,  # KEEP_RESOLUTION <ParameterBoolean>
                5,  # RTYPE <ParameterSelection>
                4,  # COMPRESS <ParameterSelection>
                1,  # JPEGCOMPRESSION <ParameterNumber>
                6,  # ZLEVEL <ParameterNumber>
                1,  # PREDICTOR <ParameterNumber>
                False,  # TILED <ParameterBoolean>
                2,  # BIGTIFF <ParameterSelection>
                False,  # TFW <ParameterBoolean>
                "",  # EXTRA <ParameterString>
                selectedOutput + '/clip_dem.tif')  # OUTPUT <OutputRaster>

            bohLayer5 = QgsRasterLayer(selectedOutput + '/clip_dem.tif',
                                       "DEM-clipped")
            boh5 = QgsRasterCalculatorEntry()
            boh5.ref = 'boh5@1'
            boh5.raster = bohLayer5
            boh5.bandNumber = 1
            entries.append(boh5)

            ## GDAL algorithm for slope
            processing.runalg('gdalogr:slope', bohLayer5, 1, False, True, True,
                              111120, selectedOutput + '/slope(percent).tif')

            bohLayer6 = QgsRasterLayer(selectedOutput + '/slope(percent).tif',
                                       "slope(percent)")
            QgsMapLayerRegistry.instance().addMapLayer(bohLayer6)
            boh6 = QgsRasterCalculatorEntry()
            boh6.ref = 'boh6@1'
            boh6.raster = bohLayer6
            boh6.bandNumber = 1
            entries.append(boh6)

            # Process calculation with input extent and resolution
            calc = QgsRasterCalculator('(boh4@1 * boh6@1) *' + km_value,
                                       selectedOutput + '/soil_risk.tif',
                                       'GTiff', bohLayer6.extent(),
                                       bohLayer6.width(), bohLayer6.height(),
                                       entries)

            calc.processCalculation()
            bohLayer4 = QgsRasterLayer(selectedOutput + '/soil_risk.tif',
                                       "Soil_Risk")
            QgsMapLayerRegistry.instance().addMapLayer(bohLayer4)
Esempio n. 29
0
class ImageryDataItem(LogItem):
    def __init__(self,
                 width,
                 height,
                 image_file,
                 depth_from,
                 depth_to,
                 parent=None):
        LogItem.__init__(self, parent)

        self.__width = width
        self.__height = height
        self.__min_z = 0
        self.__max_z = 100

        self.__layer = QgsRasterLayer(image_file, "rl")
        QgsProject.instance().addMapLayers([self.__layer], False)
        self.__image_depth_range = (depth_from, depth_to)

        # unused for now
        self.__x_offset = 0

    def boundingRect(self):
        return QRectF(0, 0, self.__width, self.__height)

    def min_depth(self):
        return self.__min_z

    def max_depth(self):
        return self.__max_z

    def set_min_depth(self, min_depth):
        self.__min_z = min_depth

    def set_max_depth(self, max_depth):
        self.__max_z = max_depth

    def height(self):
        return self.__height

    def set_height(self, height):
        self.__height = height

    #def move_right(self):
    #    self.__x_offset -= 10.0 / self.__width * self.__layer.width()
    #    self.update()
    #def move_left(self):
    #    self.__x_offset += 10.0 / self.__width * self.__layer.width()
    #    self.update()

    def paint(self, painter, option, widget):
        self.draw_background(painter)
        painter.setClipRect(0, 0, self.__width - 1, self.__height - 2)

        image_depth = (self.__image_depth_range[1] -
                       self.__image_depth_range[0])
        ymin = -(self.__max_z - self.__image_depth_range[0]
                 ) / image_depth * self.__layer.height()
        ymax = -(self.__min_z - self.__image_depth_range[0]
                 ) / image_depth * self.__layer.height()

        # we need to also set the width of the extent according to the aspect ratio
        # so that QGIS allows to "zoom in"
        ar = float(self.__layer.width()) / self.__layer.height()
        nw = ar * (ymax - ymin)

        lext = QgsRectangle(self.__x_offset, ymin, self.__x_offset + nw - 1,
                            ymax)

        # QgsMapSettings.setExtent() recomputes the given extent
        # so that the scene is centered
        # We reproduce here this computation to set the raster
        # x coordinate to what we want

        mw = float(self.__width - 2)
        mh = float(self.__height - 2)
        mu_p_px_y = lext.height() / mh
        mu_p_px_x = lext.width() / mw
        dxmin = lext.xMinimum()
        dxmax = lext.xMaximum()
        dymin = lext.yMinimum()
        dymax = lext.yMaximum()
        if mu_p_px_y > mu_p_px_x:
            mu_p_px = mu_p_px_y
            whitespace = ((mw * mu_p_px) - lext.width()) * 0.5
            dxmin -= whitespace
            dxmax += whitespace
        else:
            mu_p_px = mu_p_px_x
            whitespace = ((mh * mu_p_px) - lext.height()) * 0.5
            dymin -= whitespace
            dymax += whitespace
        lext = QgsRectangle(dxmin + whitespace, dymin, dxmax + whitespace,
                            dymax)

        ms = QgsMapSettings()
        ms.setExtent(lext)
        ms.setOutputSize(QSize(mw, mh))
        ms.setLayers([self.__layer])
        if self.selected():
            ms.setBackgroundColor(QColor("#ffff66"))
        job = QgsMapRendererCustomPainterJob(ms, painter)

        painter.translate(1, 1)
        job.start()
        job.waitForFinished()
        painter.translate(-1, -1)
Esempio n. 30
0
gt = dem.GetGeoTransform()
xorigin, xcellsize, xrotation, yorigion, yrotation, ycellsize = gt
# Get and Print Projection Information
projInfo=dem .GetProjection()
print projInfo

demLayer  = QgsRasterLayer(os.path.join(input_Dir,dem_filename), "dem")
if not demLayer.isValid(): print "DEM Layer failed to load!"

# Load raster layer into canvas
QgsMapLayerRegistry.instance().addMapLayer(demLayer)
 
# Print Extent of the DEM layer (for use with raster calculator)
print demLayer.extent().xMinimum(), demLayer.extent().xMaximum()
print demLayer.extent().yMinimum(), demLayer.extent().yMaximum()
print demLayer.width(), demLayer.height()
name = demLayer.name()
print name
bands = demLayer.bandCount()
print bands

# Slope layer
degslopeLayer = QgsRasterLayer(os.path.join(input_Dir,'slope_dec.tif'), "Degrees_Slope")
if not degslopeLayer.isValid(): print "Slope (decimal degrees) Layer failed to load!"
# Load raster layer into canvas
QgsMapLayerRegistry.instance().addMapLayer(degslopeLayer)

# Aspect layer
degaspectLayer = QgsRasterLayer(os.path.join(input_Dir,'aspect_dec.tif'), "Degrees_Aspect")
if not degaspectLayer.isValid(): print "Aspect (decimal degrees) Layer failed to load!"
# Load raster layer into canvas
Esempio n. 31
0
class TestQGISRasterTools(unittest.TestCase):

    def setUp(self):
        self.raster = QgsRasterLayer(RASTER_BASE + '.tif', 'test')
        self.provider = self.raster.dataProvider()
        self.extent = self.raster.extent()
        self.x_res = self.raster.rasterUnitsPerPixelX()
        self.y_res = self.raster.rasterUnitsPerPixelY()

    def test_pixels_to_points(self):
        points = pixels_to_points(
            self.raster, threshold_min=1.0, threshold_max=1.5)

        # There are four such pixels only
        self.assertEquals(points.featureCount(), 4)
        for point in points.dataProvider().getFeatures():
            point = point.geometry().asPoint()

            # Move point in center of the pixels and get the value
            value = self.provider.identify(
                QgsPoint(
                    point.x() + 0.5 * self.x_res,
                    point.y() - 0.5 * self.y_res),
                QgsRaster.IdentifyFormatValue,
                self.extent)
            value = value.results()[1]
            self.assertGreater(value, 1.0)
            self.assertLess(value, 1.5)

        # Infinite threshold test
        points = pixels_to_points(self.raster, threshold_min=1.1)
        self.assertEquals(points.featureCount(), 8)
        for point in points.dataProvider().getFeatures():
            point = point.geometry().asPoint()

            # Move point in center of the pixels and get the value
            value = self.provider.identify(
                QgsPoint(
                    point.x() + 0.5 * self.x_res,
                    point.y() - 0.5 * self.y_res),
                QgsRaster.IdentifyFormatValue,
                self.extent)
            value = value.results()[1]
            self.assertGreater(value, 1.1)
    test_pixels_to_points.slow = True

    def test_polygonize(self):
        """Test if polygonize works"""
        geometry = polygonize(
            self.raster, threshold_min=1.0, threshold_max=1.5)
        # Result is one square
        self.assertTrue(geometry.isGeosValid())
        self.assertFalse(geometry.isMultipart())

        # noinspection PyArgumentEqualDefault
        geometry = polygonize(self.raster, threshold_min=0.0)
        # Result is several polygons
        self.assertTrue(geometry.isGeosValid())
        self.assertTrue(geometry.isMultipart())

        expected = QgsVectorLayer(VECTOR_BASE + '.shp', 'test', 'ogr')
        for feature in expected.getFeatures():
            # the layer has one feature only
            expected_geom = feature.geometry()
            self.assertTrue((geometry.isGeosEqual(expected_geom)))
    test_polygonize.slow = True

    def test_clip_raster(self):
        """Test clip_raster work"""
        new_raster = clip_raster(
            self.raster,
            self.raster.width(),
            self.raster.height(),
            self.extent
        )

        self.assertEqual(self.raster.rasterUnitsPerPixelY(),
                         new_raster.rasterUnitsPerPixelY())
        self.assertEqual(self.raster.rasterUnitsPerPixelX(),
                         new_raster.rasterUnitsPerPixelX())
        self.assertEqual(self.raster.extent(),
                         new_raster.extent())
        self.assertEqual(self.raster.width(),
                         new_raster.width())
        self.assertEqual(self.raster.height(),
                         new_raster.height())

        # Set extent as 1/2 of self.extent
        center = self.extent.center()
        x_max, y_max = center.x(), center.y()
        new_extent = QgsRectangle(
            self.extent.xMinimum(),
            self.extent.yMinimum(),
            x_max,
            y_max
        )
        new_raster = clip_raster(
            self.raster,
            self.raster.width(),
            self.raster.height(),
            new_extent
        )
        self.assertAlmostEquals(
            self.raster.rasterUnitsPerPixelY(),
            2 * new_raster.rasterUnitsPerPixelY())
        self.assertAlmostEquals(
            self.raster.rasterUnitsPerPixelX(),
            2 * new_raster.rasterUnitsPerPixelX())
        self.assertEqual(new_extent, new_raster.extent())
        self.assertEqual(self.raster.width(), new_raster.width())
        self.assertEqual(self.raster.height(), new_raster.height())
    test_clip_raster.slow = True
Esempio n. 32
0
pcolor = []

pcolor.append(QgsColorRampShader.ColorRampItem(1, QColor("#d2ca97")))
pcolor.append(QgsColorRampShader.ColorRampItem(2, QColor("#f7f7f7")))
pcolor.append(QgsColorRampShader.ColorRampItem(3, QColor("#a1d99b")))
pcolor.append(QgsColorRampShader.ColorRampItem(4, QColor("#41ab5d")))
pcolor.append(QgsColorRampShader.ColorRampItem(5, QColor("#006d2c")))
pcolor.append(QgsColorRampShader.ColorRampItem(6, QColor("#00441b")))

renderer = QgsPalettedRasterRenderer(layer.dataProvider(), 1,
                                     QgsPalettedRasterRenderer.colorTableToClassData(pcolor))
layer.setRenderer(renderer)

extent = layer.extent()
width, height = layer.width(), layer.height()
renderer = layer.renderer()
provider = layer.dataProvider()
crs = layer.crs().toWkt()
pipe = QgsRasterPipe()
pipe.set(provider.clone())
pipe.set(renderer.clone())
file_writer = QgsRasterFileWriter("C:/temp/naip/classified_res.tif")
file_writer.writeRaster(pipe,
                        width,
                        height,
                        extent,
                        layer.crs())

print("Done!")
Esempio n. 33
0
def main_function(tif_file_name,
                  output_file_name,
                  input_directory=INPUT_DIRECTORY,
                  output_directory=OUTPUT_DIRECTORY):
    """The main function to calculate NDVI from tif file in `tif_path` to `output_path`
    """
    full_tif_path = os.path.join(input_directory, tif_file_name)
    full_output_path = os.path.join(output_directory, output_file_name)
    if not os.path.exists(full_tif_path):
        print('TIF file %s is not exist' % full_tif_path)
    else:
        print('TIF file %s is exist' % full_tif_path)

    #### Prepare QGIS ####
    import sys
    import qgis.utils

    from qgis.core import (QgsApplication, QgsProcessingFeedback,
                           QgsVectorLayer, QgsProcessingProvider,
                           QgsProcessingRegistry, QgsRasterLayer, QgsProject)
    from qgis.analysis import QgsNativeAlgorithms

    # See https://gis.stackexchange.com/a/155852/4972 for details about the prefix
    QgsApplication.setPrefixPath('/usr', True)
    qgs = QgsApplication([], False)
    qgs.initQgis()

    #  # Append the path where processing plugin can be found
    sys.path.append('/usr/share/qgis/python/plugins/')

    import processing
    from processing.core.Processing import Processing
    Processing.initialize()
    QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())

    #### Add NDVI Provider ####
    provider = NDVIProvider()
    provider.loadAlgorithms()

    QgsApplication.processingRegistry().addProvider(provider)

    #### Run split bands algorithm ####
    # algorithm id:
    split_band_algorithm_id = 'uas:Split_bands'
    # parameters
    split_band_algorithm_parameters = {
        'inputimage': full_tif_path,
        'Red': os.path.join(TEMP_DIRECTORY, 'red.sdat'),
        'Green': os.path.join(TEMP_DIRECTORY, 'green.sdat'),
        'Blue': os.path.join(TEMP_DIRECTORY, 'nir.sdat'),
        'R_conv': os.path.join(OUTPUT_DIRECTORY, 'red_conv.tif'),
        'G_conv': os.path.join(OUTPUT_DIRECTORY, 'green_conv.tif'),
        'B_conv': os.path.join(OUTPUT_DIRECTORY, 'nir_conv.tif'),
    }
    # Run algorithm
    split_band_result = processing.run(split_band_algorithm_id,
                                       split_band_algorithm_parameters)

    # Check result
    print('Path of G_conv: %s is exist = %s' %
          (split_band_result.get('G_conv'),
           os.path.exists(split_band_result.get('G_conv'))))
    print('Path of R_conv: %s is exist = %s' %
          (split_band_result.get('R_conv'),
           os.path.exists(split_band_result.get('R_conv'))))

    #### Run NDVI raster calculation algorithm ####
    # algorithm id:
    ndvi_algorithm_id = 'uas:Calculate_NDVI'
    # parameters
    ndvi_algorithm_parameters = {
        'inputnirband': split_band_result['B_conv'],
        'inputredband': split_band_result['R_conv'],
        'Output': full_output_path
    }
    if False:
        # Run algorithm
        ndvi_result = processing.run(ndvi_algorithm_id,
                                     ndvi_algorithm_parameters)

        # Check result
        print('Path of NDVI: %s is exist = %s' %
              (ndvi_result.get('Output'),
               os.path.exists(ndvi_result.get('Output'))))
    else:
        from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry

        entries = []

        nir_layer = QgsRasterLayer(ndvi_algorithm_parameters['inputnirband'],
                                   "nir")
        QgsProject.instance().addMapLayer(nir_layer)
        nir = QgsRasterCalculatorEntry()
        nir.ref = 'nir@1'
        nir.raster = nir_layer
        nir.bandNumber = 1
        entries.append(nir)

        red_layer = QgsRasterLayer(ndvi_algorithm_parameters['inputredband'],
                                   "red")
        QgsProject.instance().addMapLayer(red_layer)
        red = QgsRasterCalculatorEntry()
        red.ref = 'red@1'
        red.raster = red_layer
        red.bandNumber = 1
        entries.append(red)

        ndvi_expression = 'Float( nir@1 - red@1 ) / Float( nir@1 + red@1 )'

        calc = QgsRasterCalculator(ndvi_expression,
                                   ndvi_algorithm_parameters['Output'],
                                   'GTiff', nir_layer.extent(),
                                   nir_layer.width(), nir_layer.height(),
                                   entries)

        a = calc.processCalculation()
        print('Result: ', a)

    # Exit QGIS
    qgs.exitQgis()
Esempio n. 34
0
    def calc_lst(self, dir_output, dir_bt_10, dir_bt_11, dir_A2, dir_A1,
                 dir_A0, temp_folder, TEMP):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_bt_10 = dir_bt_10
        self.dir_bt_11 = dir_bt_11
        self.dir_A2 = dir_A2
        self.dir_A1 = dir_A1
        self.dir_A0 = dir_A0
        self.dir_output_temp = self.path + 'SPT.tif'

        self.TEMP = TEMP

        entries = []

        band10 = QgsRasterLayer(self.dir_bt_10)
        ras = QgsRasterCalculatorEntry()
        ras.ref = '10 - BT@1'
        ras.raster = band10
        ras.bandNumber = 1
        entries.append(ras)

        band11 = QgsRasterLayer(self.dir_bt_11)
        ras = QgsRasterCalculatorEntry()
        ras.ref = '11 - BT@1'
        ras.raster = band11
        ras.bandNumber = 1
        entries.append(ras)

        A2 = QgsRasterLayer(self.dir_A2)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'A2@1'
        ras.raster = A2
        ras.bandNumber = 1
        entries.append(ras)

        A1 = QgsRasterLayer(self.dir_A1)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'A1@1'
        ras.raster = A1
        ras.bandNumber = 1
        entries.append(ras)

        A0 = QgsRasterLayer(self.dir_A0)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'A0@1'
        ras.raster = A0
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator(
                '(("A0@1" + "A1@1" * "10 - BT@1" - "A2@1" * "11 - BT@1") - 273.15)'
                + self.TEMP, self.dir_output_temp, 'GTiff', A0.extent(),
                A0.width(), A0.height(), entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator(
                '(("A0@1" + "A1@1" * "10 - BT@1" - "A2@1" * "11 - BT@1") - 273.15)'
                + self.TEMP, self.dir_output, 'GTiff', A0.extent(), A0.width(),
                A0.height(), entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))