예제 #1
0
    def loadCloudIntoQGIS(self):
        try:
            # loadCloudButton ascFileNameLineEdit pointCloudPathLineEdit stepSizeSpinBox blast2demGroupBox consoleCommandPlainTextEdit
            self.dlg.selectCloudButton.setEnabled(False)
            self.dlg.loadCloudButton.setEnabled(False)
            self.dlg.ascFileNameLineEdit.setEnabled(False)
            self.dlg.pointCloudPathLineEdit.setEnabled(False)
            self.dlg.stepSizeSpinBox.setEnabled(False)
            self.dlg.blast2demGroupBox.setEnabled(False)
            self.dlg.pageDescPlainTextEdit.setEnabled(False)

            #cloudfile = self.PotreeCraftSupport.lasconvert_isready(r'c:\PotreeConverter_16\3DModel_Pcld_LASCloud.las', '-rgb', '0.1')
            cloudfile = self.PotreeCraftSupport.lasconvert_isready(
                self.dlg.pointCloudPathLineEdit.text(), self.ascParam,
                self.dlg.stepSizeSpinBox.text().replace(',', '.'))
            self.dlg.ascFileNameLineEdit.setText(cloudfile)
            print(self.PotreeCraftSupport.potreeconverterpath + cloudfile)
            # add raster layer
            fileInfo = QFileInfo(self.PotreeCraftSupport.potreeconverterpath +
                                 cloudfile)
            print(fileInfo)
            path = fileInfo.filePath()
            baseName = fileInfo.baseName()

            layer = QgsRasterLayer(path, baseName)
            QgsProject.instance().addMapLayer(layer)

            if layer.isValid() is True:
                print("Layer was loaded successfully!")
            else:
                print(
                    "Unable to read basename and file path - Your string is probably invalid"
                )

            self.dlg.selectCloudButton.setEnabled(True)
            self.dlg.loadCloudButton.setEnabled(True)
            self.dlg.ascFileNameLineEdit.setEnabled(True)
            self.dlg.pointCloudPathLineEdit.setEnabled(True)
            self.dlg.stepSizeSpinBox.setEnabled(True)
            self.dlg.blast2demGroupBox.setEnabled(True)
            self.dlg.pageDescPlainTextEdit.setEnabled(True)

        except Exception as genex:
            print('PYTHON EXCEPTOIN CAUGHT:')
            print(str(genex))
            self.dlg.selectCloudButton.setEnabled(True)
            self.dlg.loadCloudButton.setEnabled(True)
            self.dlg.ascFileNameLineEdit.setEnabled(True)
            self.dlg.pointCloudPathLineEdit.setEnabled(True)
            self.dlg.stepSizeSpinBox.setEnabled(True)
            self.dlg.blast2demGroupBox.setEnabled(True)
            self.dlg.pageDescPlainTextEdit.setEnabled(True)
예제 #2
0
 def loadWebService(self):
     # get selected items and add to the map
     self.bar.show()
     EPSG_CODE_4326 = 'EPSG:4326'
     selectedServices = self.getSelectedItemsFromTable()
     web_map_service = self.generatedService.web_map_service
     for selectedService in selectedServices:
         if self.generatedService.service_url is not None:
             layer_name = selectedServices[selectedService].name
             url = 'contextualWMSLegend=0'
             if hasattr(web_map_service[layer_name], 'crsOptions'):
                 if len(web_map_service[layer_name].crsOptions) > 0:
                     if EPSG_CODE_4326 in web_map_service[
                             layer_name].crsOptions:
                         url += '&crs=' + EPSG_CODE_4326
                         if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                             url += '&tileMatrixSet=' + EPSG_CODE_4326
                     else:
                         url += '&crs=' + web_map_service[
                             layer_name].crsOptions[0]
                         if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                             url += '&tileMatrixSet=' + web_map_service[
                                 layer_name].crsOptions[0]
             else:
                 url += '&crs=' + EPSG_CODE_4326
                 if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                     url += '&tileMatrixSet=' + EPSG_CODE_4326
             url += '&dpiMode=7&featureCount=10&format=image/png&styles' + \
                    '&layers=' + layer_name + \
                    '&url=' + str(self.generatedService.service_url)
             rlayer = QgsRasterLayer(
                 url, selectedServices[selectedService].title, 'wms')
             if not rlayer.isValid():
                 QMessageBox.information(
                     None, "ERROR:", 'Imposible cargar las capas ' +
                     selectedServices[selectedService].title +
                     ' en este momento.')
             else:
                 QgsProject.instance().addMapLayer(rlayer)
                 self.iFace.messageBar().pushMessage(
                     "Mensaje:",
                     "Fueron cargadas las capas WMS con exito",
                     level=Qgis.Success,
                     duration=3)
         else:
             QMessageBox.information(
                 None, "ERROR:",
                 'No selecciono ninguna capa WMS para cargar')
     self.bar.close()
예제 #3
0
 def on_pushButton_clicked(self, name='s'):
     if name == 's':
         return
     img = self.img3
     if MOOD == "OPENCV":
         #change img(2D) to 1D
         img1 = img.reshape((img.shape[0] * img.shape[1], 3))
         img1 = np.float32(img1)
         criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10,
                     1.0)
         flags = cv2.KMEANS_RANDOM_CENTERS
         compactness, labels, centers = cv2.kmeans(img1,
                                                   self.spinBox.value(),
                                                   None, criteria, 10,
                                                   flags)
     if MOOD == "MY_KMEAN":
         r = img.shape[0] * img.shape[1] / (self.spinBox.value() + 1)
         z = []
         for i in range(self.spinBox.value()):
             z.append(i * r)
         img1 = img.reshape((img.shape[0] * img.shape[1], 3))
         img1 = np.float32(img1)
         tree = main(img1, z)
         for i in len(img1):
             img1[i] = tree[i]
     img2 = labels.reshape((img.shape[0], img.shape[1]))
     cv2.imwrite(self.layerName.text(), img2)
     layer = QgsRasterLayer(self.layerName.text(), 'result')
     QgsProject.instance().addMapLayer(layer)
예제 #4
0
 def on_begin_clicked(self, bol=2):
     if bol == 2:
         return
     theta, dx, dy = icp(self.Timage, self.Simage, float(self.Theta.text()),
                         float(self.Dx.text()), float(self.Dy.text()))
     res = afterImg(theta, dx, dy)
     cv2.imwrite(self.OutputName.text(), res)
     layer = QgsRasterLayer(self.OutputName.text(), 'ICP_result')
     QgsProject.instance().addMapLayer(layer)
예제 #5
0
 def loadWebService(self):
     # get selected items and add to the map
     self.bar.show()
     EPSG_CODE_4326 = 'EPSG:4326'
     selectedServices = self.getSelectedItemsFromTable()
     web_map_service = self.generatedService.web_map_service
     for selectedService in selectedServices:
         if self.generatedService.service_url is not None:
             layer_name = selectedServices[selectedService].name
             url = 'contextualWMSLegend=0'
             if hasattr(web_map_service[layer_name], 'crsOptions'):
                 if len(web_map_service[layer_name].crsOptions) > 0:
                     if EPSG_CODE_4326 in web_map_service[layer_name].crsOptions:
                         url += '&crs=' + EPSG_CODE_4326
                         if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                                 url += '&tileMatrixSet=' + EPSG_CODE_4326
                     else:
                         url += '&crs=' + web_map_service[layer_name].crsOptions[0]
                         if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                                 url += '&tileMatrixSet=' + web_map_service[layer_name].crsOptions[0]
             else:
                 url += '&crs=' + EPSG_CODE_4326
                 if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                     url += '&tileMatrixSet=' + EPSG_CODE_4326
             url += '&dpiMode=7&featureCount=10&format=image/png&styles' + \
                    '&layers=' + layer_name + \
                    '&url=' + str(self.generatedService.service_url)
             rlayer = QgsRasterLayer(url, selectedServices[selectedService].title, 'wms')
             if not rlayer.isValid():
                 QMessageBox.information(None, "ERROR:", 'Unable to load ' +
                                         selectedServices[selectedService].title +
                                         ' this layer now.')
             else:
                 QgsProject.instance().addMapLayer(rlayer)
         else:
             QMessageBox.information(None, "ERROR:", 'Service url is None')
     self.bar.close()
예제 #6
0
    def carregamapa(self, tmap=3):
        from ..model.utils import msgLog

        root = QgsProject.instance().layerTreeRoot()
        urlWithParams = 'type=xyz&url=http://mt1.google.com/vt/lyrs%3Ds%26x%3D%7Bx%7D%26y%3D%7By%7D%26z%3D%7Bz%7D&zmax=19&zmin=0'
        rlayer = QgsRasterLayer(urlWithParams, 'Google Satellite', 'wms')
        if rlayer.isValid():
            QgsProject.instance().addMapLayer(rlayer, False)
            root.addLayer(rlayer)
        else:
            msgLog('Failed to load Satellite layer')

        urlWithParams = 'type=xyz&url=http://mt1.google.com/vt/lyrs%3Dt%26x%3D%7Bx%7D%26y%3D%7By%7D%26z%3D%7Bz%7D&zmax=19&zmin=0'
        rlayer = QgsRasterLayer(urlWithParams, 'Google Terrain', 'wms')
        if rlayer.isValid():
            QgsProject.instance().addMapLayer(rlayer, False)
            root.addLayer(rlayer)
        else:
            msgLog('Failed to load Terrain layer')
예제 #7
0
    def executeCropRowsClipProcessing(self):
        """Execute Crop Rows STEP 1"""
        QgsMessageLog.logMessage(
            'Excecute Task1: Clip Raster Mosaic by Vector Mask')
        strMosaicRasterFileSelected = self.dlg.comboBoxInputRaster.currentText(
        )
        strMaskVectorFileSelected = self.dlg.comboBoxInputVector.currentText()

        seedValue = 0
        QgsMessageLog.logMessage('Get Seed from user selection')
        if self.dlg.radioButtonSeed1.isChecked() == True:
            seedValue = 1
        elif self.dlg.radioButtonSeed2.isChecked() == True:
            seedValue = 2
        elif self.dlg.radioButtonSeed3.isChecked() == True:
            seedValue = 3
        elif self.dlg.radioButtonSeed4.isChecked() == True:
            seedValue = 4

        if (seedValue == 0):
            QgsMessageLog.logMessage('You must be set a seed value !')
            QMessageBox.critical(None, 'Error!',
                                 "You must be set a <b>seed</b> value !",
                                 QMessageBox.Ok)
            pass
        else:
            QgsMessageLog.logMessage('Seed value: ' + str(seedValue))

        #Start Crop Rows processing
        if strMosaicRasterFileSelected != '' and strMaskVectorFileSelected != '' and seedValue > 0 and self.flagClipTaskDone == 0:
            if self.flagNoCropRaster == False:
                msgboxCrop = "Are you sure that you want to start a <b>Mosaic Clip by Mask</b> process?<br>Keep in mind this task can take a few minutes, even several hours."
            else:
                msgboxCrop = "Are you sure that you want to copy a raster <b>Mosaic</b> into a selected shared folder?<br>Keep in mind this process can take a few minutes, even several hours."
            ret = QMessageBox.question(None, "Mosaic Data Preprocessing",
                                       (msgboxCrop),
                                       QMessageBox.Yes | QMessageBox.No,
                                       QMessageBox.Yes)
            if ret == QMessageBox.Yes:
                #hide step1 button
                self.dlg.btnExecuteClippingTask.setVisible(False)
                QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)

                self.dlg.statusBarProcessing.setGeometry(10, 281, 631, 31)

                self.dlg.statusBarProcessing.setValue(1)
                QgsMessageLog.logMessage('Processing Raster ')
                #urlSourceRasterMosaic = QgsMapLayerRegistry.instance().mapLayersByName(strMosaicRasterFileSelected)[0].dataProvider().dataSourceUri()
                urlSourceRasterMosaic = QgsProject.instance().mapLayersByName(
                    strMosaicRasterFileSelected)[0].dataProvider(
                    ).dataSourceUri()
                self.dlg.statusBarProcessing.setValue(5)
                #urlSourceVectorMask = QgsMapLayerRegistry.instance().mapLayersByName(strMaskVectorFileSelected)[0].dataProvider().dataSourceUri()
                urlSourceVectorMask = QgsProject.instance().mapLayersByName(
                    strMaskVectorFileSelected)[0].dataProvider().dataSourceUri(
                    )
                self.dlg.statusBarProcessing.setValue(10)
                urlSourceVectorMaskSplit = urlSourceVectorMask.split("|")[0]
                self.dlg.statusBarProcessing.setValue(20)
                temporalPath = self.dlg.inputSharedFolderPath.text().replace(
                    "/", "\\")
                rasterLyr = QgsRasterLayer(urlSourceRasterMosaic, "masklayer")
                pixelSizeX = rasterLyr.rasterUnitsPerPixelX()
                pixelSizeY = rasterLyr.rasterUnitsPerPixelY()
                self.dlg.statusBarProcessing.setValue(25)

                QgsMessageLog.logMessage(str(urlSourceRasterMosaic))
                QgsMessageLog.logMessage(str(urlSourceVectorMaskSplit))
                QgsMessageLog.logMessage('GDAL Clipper')
                QgsMessageLog.logMessage(str(pixelSizeX))
                QgsMessageLog.logMessage(str(pixelSizeY))

                gdalOSGeoPath = self.dlg.inputGdalOsgeoPath.text().replace(
                    "/", "\\")
                #temporalPath = self.dlg.inputSharedFolderPath.text().replace("/", "\\")
                self.dlg.statusBarProcessing.setValue(30)
                timestr = time.strftime("%Y%m%d-%H%M%S")
                ouputFilenameRasterClip = 'clipfile_' + timestr + '.tif'
                ouputFilenameVectorMask = 'maskfile_' + timestr + '.shp'
                ouputFilenamePrj = 'croprows_' + timestr
                ouputFilenameCropRowsProjectXML = 'croprows_' + timestr + '.xml'
                ouputclipfile_path = os.path.join(temporalPath,
                                                  ouputFilenameRasterClip)
                #temporalPath.replace("/", "\\") + ouputFilenameRasterClip
                self.dlg.statusBarProcessing.setValue(35)

                if self.flagNoCropRaster == True:
                    QgsMessageLog.logMessage(
                        'No Crop option selected - Copy file directly')
                    shutil.copyfile(
                        urlSourceRasterMosaic,
                        os.path.join(ouputclipfile_path[:-4] + '.tif'))
                    self.dlg.statusBarProcessing.setValue(40)
                else:
                    QgsMessageLog.logMessage(
                        'Crop raster by mask option selected - Cliping using GDAL'
                    )
                    #print('C:/Program Files/QGIS 2.14/bin/gdalwarp')
                    gdalWarpSubProcessCommand = '"' + gdalOSGeoPath + "\\" + 'gdalwarp.exe" -dstnodata -9999 -q -cutline ' + urlSourceVectorMaskSplit.replace(
                        "/", "\\") + ' -crop_to_cutline -tr ' + str(
                            pixelSizeX) + ' ' + str(
                                pixelSizeX
                            ) + ' -of GTiff ' + urlSourceRasterMosaic.replace(
                                "/", "\\") + ' ' + ouputclipfile_path
                    QgsMessageLog.logMessage(str(gdalWarpSubProcessCommand))
                    self.dlg.statusBarProcessing.setValue(40)
                    p = subprocess.Popen(gdalWarpSubProcessCommand,
                                         shell=True,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.STDOUT)
                    for line in p.stdout.readlines():
                        print(line),
                        retval = p.wait()

                self.dlg.statusBarProcessing.setValue(50)
                QgsMessageLog.logMessage(
                    'Clipper process done check result file ' +
                    ouputclipfile_path)
                #Load result file into map environment
                rasterLayerClipped = QgsRasterLayer(
                    ouputclipfile_path, ouputFilenameRasterClip[:-4])

                pixelSizeXClip = rasterLayerClipped.rasterUnitsPerPixelX()
                pixelSizeYClip = rasterLayerClipped.rasterUnitsPerPixelY()

                imageWClip = rasterLayerClipped.width()
                imageHClip = rasterLayerClipped.height()

                providerRasterLayerClipped = rasterLayerClipped.dataProvider()
                extentRasterLayerClipped = rasterLayerClipped.extent()

                #print(providerRasterLayerClipped)
                #xmin,ymax,xmax,ymin
                imageXminClip = (extentRasterLayerClipped.xMinimum())
                imageYminClip = (extentRasterLayerClipped.yMinimum())
                imageXmaxClip = (extentRasterLayerClipped.xMaximum())
                imageYmaxClip = (extentRasterLayerClipped.yMaximum())
                #origin
                imageXOriginClip = int(
                    round(extentRasterLayerClipped.xMinimum()))
                imageYOriginClip = int(
                    round(extentRasterLayerClipped.yMinimum()))
                #epsg

                proj4crs = rasterLayerClipped.crs()

                QgsMessageLog.logMessage(str(proj4crs.srsid()))
                QgsMessageLog.logMessage(str(proj4crs.toProj4()))
                QgsMessageLog.logMessage(str(proj4crs.authid()))
                QgsMessageLog.logMessage(str(proj4crs.description()))
                QgsMessageLog.logMessage(str(proj4crs.ellipsoidAcronym()))
                QgsMessageLog.logMessage(str(proj4crs.findMatchingProj()))
                QgsMessageLog.logMessage(str(proj4crs.postgisSrid()))
                QgsMessageLog.logMessage(str(proj4crs.toWkt()))

                epsgClip = proj4crs.postgisSrid()
                epsgWKTClip = proj4crs.toWkt()

                #QgsMapLayerRegistry.instance().addMapLayer(rasterLayerClipped)
                QgsProject.instance().addMapLayer(rasterLayerClipped)
                #pass

                self.dlg.statusBarProcessing.setValue(75)
                #copy vector mask
                outputFileMaskPath = os.path.join(temporalPath,
                                                  ouputFilenameVectorMask)
                #temporalPath.replace("/", "\\") + ouputFilenameVectorMask
                temporalVectorLayer = QgsVectorLayer(urlSourceVectorMaskSplit,
                                                     "tmp_polygon", "ogr")
                shutil.copyfile(urlSourceVectorMaskSplit[:-4] + '.shp',
                                os.path.join(outputFileMaskPath[:-4] + '.shp'))
                shutil.copyfile(urlSourceVectorMaskSplit[:-4] + '.dbf',
                                os.path.join(outputFileMaskPath[:-4] + '.dbf'))
                shutil.copyfile(urlSourceVectorMaskSplit[:-4] + '.shx',
                                os.path.join(outputFileMaskPath[:-4] + '.shx'))
                temporalVectorLayerDataProvider = temporalVectorLayer.dataProvider(
                )
                temporalVectorLayerCrs = temporalVectorLayerDataProvider.crs()
                temporalVectorLayerCrsString = temporalVectorLayerCrs.authid()
                temporalVectorLayerEPSGInt = int(
                    temporalVectorLayerCrsString[5:])

                QgsMessageLog.logMessage(str(temporalVectorLayerEPSGInt))
                maskVectorLayerExported = QgsVectorLayer(
                    outputFileMaskPath, ouputFilenameVectorMask[:-4], "ogr")
                crs = maskVectorLayerExported.crs()
                crs.createFromId(temporalVectorLayerEPSGInt)
                maskVectorLayerExported.setCrs(crs)
                maskVectorLayerExported.setCrs(
                    QgsCoordinateReferenceSystem(
                        temporalVectorLayerEPSGInt,
                        QgsCoordinateReferenceSystem.EpsgCrsId))

                styleBoundary = os.path.join(
                    (os.path.dirname(os.path.abspath(__file__))), 'styles',
                    'croprows_style_boundary.qml')
                maskVectorLayerExported.loadNamedStyle(styleBoundary)
                #QgsMapLayerRegistry.instance().addMapLayer(maskVectorLayerExported)
                QgsProject.instance().addMapLayer(maskVectorLayerExported)

                #end copy vector mask

                #TODO: try not to simulate process status, make it real
                for i in range(76, 90):
                    self.dlg.statusBarProcessing.setValue(i)

                #show step2 button
                self.dlg.btnExecuteProcessingFromApi.setVisible(True)

                self.dlg.statusBarProcessing.setValue(95)

                arrXMLOptions = [
                    str(seedValue),
                    str(ouputFilenameRasterClip),
                    str(ouputFilenameVectorMask),
                    str(pixelSizeXClip) + ',-' + str(pixelSizeYClip),
                    str(imageWClip) + ',' + str(imageHClip),
                    str(imageXminClip) + ',' + str(imageYminClip) + ',' +
                    str(imageXmaxClip) + ',' + str(imageYmaxClip),
                    str(imageXOriginClip) + ',' + str(imageYOriginClip),
                    str(epsgClip),
                    str(epsgWKTClip),
                    str(ouputFilenamePrj)
                ]

                #Write XML file
                self.writeXMLFile(ouputFilenameCropRowsProjectXML,
                                  arrXMLOptions)

                self.dlg.xmlCoreFile.setText(
                    str(ouputFilenameCropRowsProjectXML))

                self.dlg.statusBarProcessing.setValue(100)

                QApplication.setOverrideCursor(QtCore.Qt.ArrowCursor)

                self.flagClipTaskDone = 1

                toStep2Msg = QMessageBox.question(
                    None, "Crop Rows processing task start",
                    ("Are you sure that you want to start a <b>Crop Rows</b> processing task ?<br>Keep in mind this process can take a few minutes, even several hours.<br><br>Make sure that <b>Crop Rows - API Server is Running before continue.</b>"
                     ), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
                if toStep2Msg == QMessageBox.Yes:
                    QgsMessageLog.logMessage('Run Step 2')
                    self.executeCropRowsProcessingFromAPI()
                    pass
                else:
                    QMessageBox.information(
                        None, 'Message !',
                        "You must be run the processing task by manually way !<br>Just click on the button <b>Processing Task (manual)</b>",
                        QMessageBox.Ok)
                    pass
            else:
                QgsMessageLog.logMessage('No Mosaic Clip Process Selected')
                pass
        else:
            QgsMessageLog.logMessage('Missing Required Parameters')
            QgsMessageLog.logMessage('strMosaicRasterFileSelected: ' +
                                     strMosaicRasterFileSelected)
            QgsMessageLog.logMessage('strMaskVectorFileSelected: ' +
                                     strMaskVectorFileSelected)
            QgsMessageLog.logMessage('seedValue: ' + str(seedValue))
            QgsMessageLog.logMessage('flagClipTaskDone: ' +
                                     str(self.flagClipTaskDone))
            QMessageBox.critical(None, 'Error!',
                                 "Missing Required Parameter !",
                                 QMessageBox.Ok)