精华内容
下载资源
问答
  • vscode_pyqgis3.bat

    2021-06-05 16:23:05
    vscode+pyqgis配置文件
  • pgAdmin3 的 PostGIS 图层查看器,基于 PyQt4 和 PyQGIS 库。 许可证: GNU/GPL v.2.0 当前版本:1.6.1 (2015.02.24) 使用这个 pgAdmin3 插件,您可以: 查看 PostGIS 图层。 它支持矢量层和栅格层。 获取图层元...
  • PyQGIS样本 目的 当您开始使用QGIS Python API(也称为“ PyQGIS”)时,最完整的文档是C ++ QGIS API文档。然后,您将依赖于 ,在线可用示例和来自的代码。现有的插件(如果您已经很擅长编程)。 为了进一步发展,...
  • PyQGIS

    2020-05-26 22:31:59
    Getting list of layer names using PyQGIS? from qgis.core import QgsProject names = [layer.name() for layer in QgsProject.instance().mapLayers().values()] print(names) this produces a list of layers ...

    Getting list of layer names using PyQGIS?

    from qgis.core import QgsProject
    names = [layer.name() for layer in QgsProject.instance().mapLayers().values()]
    print(names)
    

    this produces a list of layers in the current project:

    ['GoogleSat', 'MyPointsLayer', 'Roads', 'House_numbers']
    

    Edit shapefile attibute

    layer = iface.activeLayer()
    selection = layer.selectedFeatures()
    layer.startEditing()
    for feature in selection:
      layer.changeAttributeValue(feature.id(), 1, 0)
    layer.commitChanges()
    

    Add raster

    from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry
    # Add raster 
    rasterpath  = r'C:\Users\wgy\Desktop\fire\test\lc08_roi.tif'
    bohLayer  = QgsRasterLayer(rasterpath, 'boh')
    if not bohLayer.isValid():  print("Layer failed to load!")
    QgsProject.instance().addMapLayer(bohLayer) # Load raster layer into canvas if needed
    entries = []
    ras = QgsRasterCalculatorEntry()
    ras.ref = 'boh@1'
    ras.raster = bohLayer
    ras.bandNumber = 1
    entries.append(ras)
    outputfile_path = r'C:\Users\wgy\Desktop\fire\test\tmp.tif'
    calc = QgsRasterCalculator( 'boh@1 > 10000', outputfile_path, 'GTiff', bohLayer.extent(), bohLayer.width(), bohLayer.height(), entries )
    calc.processCalculation()
    

    Do the reproject to a raster data:

    rlayer = QgsProject.instance().mapLayersByName('tmp')[0]
    parameter = {'INPUT': rlayer,\
        'TARGET_CRS': 'EPSG:32610', \
        'OUTPUT': r'C:/Users/wgy/Desktop/fire/test/tmp1.tif'}
    processing.run('qgis:reprojectlayer', parameter)
    

    the tutorial of raster calculator

    outLayerName = 'rndbr_tmp'
    lyr = QgsProject.instance().mapLayersByName(outLayerName)[0]
    QgsProject.instance().removeMapLayer(lyr.id())
    layername = 'ca3958812158520171009_20171004_20171105_rdnbr'
    dir_path = r'C:\Users\wgy\Desktop\literature\forestFire\postFire\c\Landsat5TMSardinia\camp\DATA\2017\fire_level_tar_files'
    lyr = QgsProject.instance().mapLayersByName(layername)[0]
    entries = []
    outputfile_path = os.path.join(dir_path, 'tiftif.tif')
    ras = QgsRasterCalculatorEntry()
    ras.ref = layername + '@1'
    ras.raster = lyr
    ras.bandNumber = 1
    entries.append(ras)
    calc = QgsRasterCalculator( ras.ref+'>400', outputfile_path, 'GTiff', lyr.extent(), lyr.width(), lyr.height(), entries )
    calc.processCalculation()
    bohLayer  = QgsRasterLayer(outputfile_path, outLayerName)
    if bohLayer.isValid():
        QgsProject.instance().addMapLayer(bohLayer)
    

    open the hdf5 file

    import os, gdal
    import numpy as np
    ## List input raster files
    os.chdir(r'C:\Users\wgy\Desktop\fire\test\goesrVSmod14a1_cloudMask')
    rasterFiles = os.listdir(os.getcwd())
    dataset = gdal.Open(rasterFiles[0], gdal.GA_ReadOnly)
    # Open raster layer
    rlayer = gdal.Open(hdflayer.GetSubDatasets()[0][0], gdal.GA_ReadOnly)
    raster_data = rlayer.ReadAsArray(0, 0, rlayer.RasterXSize, rlayer.RasterYSize)
    for i in np.arange(raster_data.shape[0]):
        print(np.unique(raster_data[i,:,:]))
    
    #*****************************************************
    # read the nc file using netCDF4
    import netCDF4
    import os
    dir_path = r'C:/Users/wgy/Desktop/fire/test/'
    input_raster = r'OR_ABI-L1b-RadC-M3C07_G16_s20183121842181_e20183121844565_c20183121845003.nc'
    database = netCDF4.Dataset(os.path.join(dir_path, input_raster))
    raster = database.variables['Rad'] # temperature variable
    raster = raster[:]
    
    #*****************************************************
    # read the TIF using rasterio
    import rasterio as rio
    import numpy as np
    dir_path = 'C:/Users/wgy/Desktop/fire/test/'
    file_name = 'c07_rad_roi.tif'
    raster = rio.open(os.path.join(dir_path, file_name))
    data = raster.read(1)
    for i in np.arange(data.shape[0]):
        for j in np.arange(data.shape[1]):
            tmp = data[i,j]!=16383
            print('%d'%tmp, end='')
            print(' ', end='')
            if j == data.shape[1]-1:
                print('')
    

    save as a tif file

    import gdal, osr, netCDF4, os
    import numpy as np
    dir_path = r'C:/Users/wgy/Desktop/fire/test/University of Wisconsin Baseline Fit/'
    input_raster = 'global_emis_inf10_location.nc'
    file_path = dir_path + input_raster
    dataset = gdal.Open("NETCDF:{0}:{1}".format(file_path, 'lat'))
    band = dataset.GetRasterBand(1)
    raster_lat = dataset.ReadAsArray(0, 0, dataset.RasterXSize, dataset.RasterYSize).astype(np.float)
    raster_lat = np.swapaxes(raster_lat, 0, 1)
    raster_lat = np.flipud(raster_lat)
    dataset = gdal.Open("NETCDF:{0}:{1}".format(file_path, 'lon'))
    band = dataset.GetRasterBand(1)
    raster_lon = dataset.ReadAsArray(0, 0, dataset.RasterXSize, dataset.RasterYSize).astype(np.float)
    raster_lon = np.swapaxes(raster_lon, 0, 1)
    raster_lon = np.flipud(raster_lon)
    input_raster = 'global_emis_inf10_monthFilled_MYD11C3.A2016306.041.nc'
    # emis1, emis2, emis3, ..., emis10, emis_flag
    file_path = dir_path + input_raster
    dataset = netCDF4.Dataset(file_path)
    raster_data = dataset.variables['emis1'][:]
    raster_data = np.swapaxes(raster_data, 0, 1)
    raster_data = np.flipud(raster_data)
    outputfile_path = os.path.join(dir_path, 'uw_bf_emis306_01.tif')
    driver = gdal.GetDriverByName("GTiff")
    dst_ds = driver.Create(outputfile_path,
                           band.YSize,
                           band.XSize,
                           1,
                           band.DataType)
    #setting extension of output raster
    # top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
    geotransform = [0 for _ in np.arange(6)]
    geotransform[0] = raster_lon[-1, -1]    # xOrigin
    geotransform[1] = 0.05                # pixelWidth
    geotransform[3] = raster_lat[0, -1]    # yOrigin
    geotransform[5] = 0.05                # pixelHeight
    dst_ds.GetRasterBand(1).WriteArray(raster_data)
    dst_ds.SetGeoTransform(geotransform)
    # setting spatial reference of output raster 
    srs = osr.SpatialReference()
    srs.ImportFromProj4('+proj=longlat +datum=WGS84 +no_defs')
    dst_ds.SetProjection(srs.ExportToWkt())
    dst_ds = None  #Close output raster dataset 
    dataset = None  #Close main raster dataset
    

    save a tif

    import gdal,osr
    import numpy as np
    import struct
    def changeRasterValues(band):
        fmttypes = {'Byte':'B', 'UInt16':'H', 'Int16':'h', 'UInt32':'I', 'Int32':'i', 'Float32':'f', 'Float64':'d'}
        data_type = band.DataType
        BandType = gdal.GetDataTypeName(band.DataType)
        raster = []
        for y in range(band.YSize):
            scanline = band.ReadRaster(0, y, band.XSize, 1, band.XSize, 1, data_type)
            values = struct.unpack(fmttypes[BandType] * band.XSize, scanline)
            raster.append(values)
        raster = [list(item) for item in raster]
        tmp = np.asarray(raster)
        # changing raster values
        for i, item in enumerate(raster):
            for j, value in enumerate(item):
                pass#raster[i][j] = int(raster[i][j] * 1000)
        raster = np.asarray(raster)  #transforming list in array
        return raster
    
    dir_path = r'C:/Users/wgy/Desktop/fire/test/'
    input_file = 'c07_rad_wgs84.tif'
    dataset = gdal.Open(os.path.join(dir_path, input_file))
    band = dataset.GetRasterBand(1)
    geotransform = dataset.GetGeoTransform()  # Get raster metadata
    outputfile_path = os.path.join(dir_path, 'c07_rad_lat_lon.tif')  # Set name of output raster
    # Create gtiff file with rows and columns from parent raster 
    driver = gdal.GetDriverByName("GTiff")
    raster1 = dataset.ReadAsArray(0, 0, dataset.RasterXSize, dataset.RasterYSize).astype(np.float)
    raster = changeRasterValues(band)
    dst_ds = driver.Create(outputfile_path, 
                           band.XSize, 
                           band.YSize, 
                           number_band, 
                           band.DataType)
    #writting output raster
    # coordinates in grid
    import rasterio
    bounds = rasterio.open(os.path.join(dir_path, input_file)).bounds
    lon = np.linspace(bounds[0], bounds[2], band.XSize+1)
    lat = np.linspace(bounds[3], bounds[1], band.YSize+1)
    latC, lonC = 0.5 * (lat[:-1] + lat[1:]), 0.5 * (lon[:-1] + lon[1:])  # center points
    latgrid, longrid = np.meshgrid(latC, lonC)  # make grid
    dst_ds.GetRasterBand(1).WriteArray(raster)
    #setting extension of output raster
    # top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
    dst_ds.SetGeoTransform(geotransform)
    # setting spatial reference of output raster 
    srs = osr.SpatialReference(wkt = prj)  # prj???
    dst_ds.SetProjection(srs.ExportToWkt())
    dst_ds = None  #Close output raster dataset 
    dataset = None  #Close main raster dataset
    

    reprojection

    dir_path = r'C:/Users/wgy/Desktop/fire/test/'
    input_raster = r'c14_rad.tif'
    input_raster = os.path.join(dir_path, input_raster)
    output_raster = r"c14_rad_epsg4326.tif"
    output_raster = os.path.join(dir_path, output_raster)
    setting = 'gdalwarp' + \
              ' ' + '-s_srs EPSG:4326' + \
              ' ' + '-t_srs EPSG:4326' + \
              ' ' + '-r near' + \
              ' ' + '-of GTiff' + \
              ' ' + input_raster + \
              ' ' + output_raster
    os.system(setting)
    

    create shp (point)

    from qgis.core import QgsFields, QgsFeature
    fn = r'C:/Users/wgy/Desktop/fire/test/newpoints.shp'
    fn = r'C:\Users\wgy\Desktop\literature\forestFire\火后\c\Landsat5TMSardinia\qinyuan\newpoints.shp'
    layerFields = QgsFields()
    layerFields.append(QgsField('id', QVariant.Int))
    layerFields.append(QgsField('value', QVariant.Double))
    layerFields.append(QgsField('name', QVariant.String))
    writer = QgsVectorFileWriter(fn, 'UTF-8', layerFields, QgsWkbTypes.Point,\
             QgsCoordinateReferenceSystem('EPSG:26912'), 'ESRI Shapefile')
    feat = QgsFeature()
    feat.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(455618, 463221)))
    feat.setAttributes([1, 1.1, 'name'])
    writer.addFeature(feat)
    iface.addVectorLayer(fn, 'points', 'ogr')
    del(writer)
    

    create shp (polygen)

    import numpy as np
    from qgis.core import QgsFields, QgsFeature
    fn = r'C:\Users\wgy\Desktop\literature\forestFire\火后\c\Landsat5TMSardinia\qinyuan\mask.shp'
    layerFields = QgsFields()
    layerFields.append(QgsField('id', QVariant.Int))
    layerFields.append(QgsField('name', QVariant.String))
    writer = QgsVectorFileWriter(fn, 'UTF-8', layerFields, QgsWkbTypes.Point,\
             QgsCoordinateReferenceSystem('EPSG:32649'), 'ESRI Shapefile')
    
    rlayer = iface.setActiveLayer()
    width = rlayer.width()
    height = rlayer.height()
    pixelX = rlayer.rasterUnitsPerPixelX()
    pixelY = rlayer.rasterUnitsPerPixelY()
    for i in np.arange(width):
        for j in np.arange(height):
            x = 618805.34299999999348074
            y = 4077616.23410000000149012
            x_cur = x + pixelX*i + pixelX/2
            y_cur = y - pixelY*j - pixelY/2
            feat = QgsFeature()
            feat.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(x_cur, y_cur)))
            feat.setAttributes([1, 'roi'])
            writer.addFeature(feat)
    
    iface.addVectorLayer(fn, 'points', 'ogr')
    del(writer)
    

    clip raster with a shapefile

    import os
    import numpy as np
    for i in np.arange(1, 12):
        dir_path = r'C:\Users\wgy\Desktop\literature\forestFire\火后\c\Landsat5TMSardinia\qinyuan\post\LC08_L1TP_125035_20190916_20190925_01_T1'
        input_raster = r'LC08_L1TP_125035_20190916_20190925_01_T1_B%d.tif' % i
        input_raster = os.path.join(dir_path, input_raster)
        output_raster = r"LC08_L1TP_125035_20190916_20190925_01_T1_B%d_roi.tif" % i
        output_raster = os.path.join(dir_path, output_raster)
        input_vector = r"roi.shp"
        input_vector = os.path.join(os.path.dirname(os.path.dirname(dir_path)), input_vector)
        if input_raster.split('.')[-1] == 'nc':
            input_raster_tmp = 'NETCDF:"{0}":{1}'.format(input_raster, 'Rad')
        elif input_raster.split('.')[-1] == 'tif':
            input_raster_tmp = '{0}'.format(input_raster)
        
        setting = 'gdalwarp' + \
            ' -of GTiff' + \
            ' -cutline ' + input_vector + \
            ' -cl roi'  + ' -crop_to_cutline' + \
            ' ' + input_raster_tmp + \
            ' ' + output_raster
        
        os.system(setting)
    

    clip raster by mask layer

    import os
    def clip_raster_by_vector(input_raster, input_vector, output_raster, overwrite=False):
        if overwrite:
            if os.path.isfile(output_raster):
                os.remove(output_raster)
        if not os.path.isfile(input_raster):
            print ("File doesn't exists", input_raster)
            return None
        else:
            if input_raster.split('.')[-1] == 'nc':
                input_raster_tmp = "NETCDF:{0}:{1}".format(input_raster, 'Rad')
            else:
                input_raster_tmp = input_raster
            dataset = gdal.Open(input_raster_tmp)
            band = dataset.GetRasterBand(1)
            data_type = band.DataType
            params = {'INPUT': input_raster,
                      'MASK': input_vector,
                      'NODATA': 0,
                      'ALPHA_BAND': False,
                      'CROP_TO_CUTLINE': True,
                      'KEEP_RESOLUTION': True,
                      'OPTIONS': 'COMPRESS=LZW',
                      'DATA_TYPE': data_type,  # Byte
                      'OUTPUT': output_raster,
                      }
            feedback = qgis.core.QgsProcessingFeedback()
            alg_name = 'gdal:cliprasterbymasklayer'
            result = processing.run(alg_name, params, feedback=feedback)
            return result
    dir_path = r'C:/Users/wgy/Desktop/fire/test/'
    input_raster = r'OR_ABI-L1b-RadC-M3C07_G16_s20183121842181_e20183121844565_c20183121845003.nc'
    input_raster = os.path.join(dir_path, input_raster)
    output_raster = r"c07_rad_roi.tif"
    output_raster = os.path.join(dir_path, output_raster)
    input_vector = r"roi.shp"
    input_vector = os.path.join(dir_path, input_vector)
    result = clip_raster_by_vector(input_raster, input_vector, output_raster, overwrite=True)
    print('result =', result)
    
    展开全文
  • Welcome to the world of PyQGIS, the blending of QGIS and Python to extend and enhance your open source GIS toolbox. With PyQGIS you can write scripts and plugins to implement new features and perform ...
  • 这是用于QGIS的Python脚本的存储库 访问 ,我在其中共享地理编程工具和教程以及地理信息系统
  • pyqgis 打包

    2020-07-31 16:25:35
    安装pyinstaller cmd管理员模式安装C:\OSGeo4W\bin\python-qgis-ltr.bat -m pip install pyinstaller 测试安装 命令行运行C:\OSGeo4W\bin\python-qgis-ltr.bat -m PyInstaller 如图所示安装成功。...
    1. 安装pyinstaller

    cmd管理员模式安装C:\OSGeo4W\bin\python-qgis-ltr.bat -m pip install pyinstaller

    1. 测试安装
      命令行运行C:\OSGeo4W\bin\python-qgis-ltr.bat -m PyInstaller
      如图所示安装成功。
      在这里插入图片描述

    2. 编写示例程序install.py

    import sys,os
    from qgis.core import QgsApplication
    from qgis.gui import QgsMapCanvas
    
    os.environ['GDAL_DATA'] = r'C:\OSGeo4W\share\gdal'
    os.environ['PROJ_LIB'] = r'C:\OSGeo4W\share\proj'
    def init():
      a = QgsApplication([], True)
      QgsApplication.setPrefixPath('qgis', True)
      QgsApplication.initQgis()
      return a
    
    def show_canvas(app):
      canvas = QgsMapCanvas()
      canvas.show()
      app.exec_()
    app = init()
    show_canvas(app)
    

    命令行运行C:\OSGeo4W\bin\python-qgis-ltr.bat install.py
    如下图所示:
    在这里插入图片描述

    1. 编写打包install.bat
    "C:\OSGeo4W\bin\python-qgis-ltr.bat" -m PyInstaller -w ^
    --icon=logo.ico ^
    --add-data="C:\OSGeo4W\apps\qgis-ltr\plugins;qgis\plugins" ^
    --add-data="C:\OSGeo4W\apps\Python37\Lib\site-packages\PyQt5\*.pyd;PyQt5" ^
    --add-data="C:\OSGeo4W\apps\qt5\plugins\styles;PyQt5\Qt\plugins\styles" ^
    --add-data="C:\OSGeo4W\apps\qt5\plugins\iconengines;PyQt5\Qt\plugins\iconengines" ^
    --add-data="C:\OSGeo4W\apps\qt5\plugins\imageformats;PyQt5\Qt\plugins\imageformats" ^
    --add-data="C:\OSGeo4W\apps\qt5\plugins\platforms;PyQt5\Qt\plugins\platforms" ^
    --add-data="C:\OSGeo4W\apps\qt5\plugins\platformthemes;PyQt5\Qt\plugins\platformthemes" ^
    install.py
    
    

    解析:C:\OSGeo4W\apps\qgis-ltr\plugins -> qgis\plugins打包时将相应的文件拷贝到指定的文件夹下。

    命令行在当前目录下执行install.bat
    执行结果如下:
    在这里插入图片描述

    1. 运行打包后的程序
      dist\install\install.exe
      在这里插入图片描述
      执行结果:
      在这里插入图片描述

    注意:QgsApplication.setPrefixPath('qgis', True)指的是打包后的安装目录。
    在这里插入图片描述
    在这里插入图片描述

    Reference

    https://blog.csdn.net/this_is_id/article/details/102974721

    展开全文
  • PyQGIS developer cookbook_2.8 是release2.8的
  • PyQgis3.4+PyCharm环境配置

    千次阅读 2019-05-27 21:08:49
    PyQgis3.4+PyCharm环境配置1题记(第一篇博客)2安装包下载2.1.下载osgeo4w2.2下载安装包2.3下载完成后的说明3配置环境3.1建立.cmd文件3.2双击pyqgis.cmd文件3.2.1问题13.3安装pb_tool3.3.1错误一3.3.2错误二3.4配置...

    1题记(第一篇博客)

    最近需要用到qgis实现缓冲区的一个功能,需要来配环境。为此看了好多博客,发现好多博客内容都是老版本的qgis,新版本的qgis和之前都不一样。而且博客内容写的并不是非常详细,作为一个完全新手完全不懂,看了那么博客,我都没有看明白到底首先装什么软件。最后经历了四天的时间,尝试了各种方法卸了装,装了卸。最后翻墙用谷歌搜到了两篇对我帮助很大的文档。但是也并不是傻瓜式安装,其中也出现了很多文档上没有出现的问题,最后摸索着终于把环境配好,示例代码运行成功,特此分享给大家。

    2安装包下载

    2.1.下载osgeo4w

    32位:http://download.osgeo.org/osgeo4w/osgeo4w-setup-x86.exe
    64位: http://download.osgeo.org/osgeo4w/osgeo4w-setup-x86_64.exe

    2.2下载安装包

    安装过程中选Advanced Install就可以下载资源包了,安装路径建议保持默认路径。当然也可以修改,只是修改后会牵涉到相应的路径变量的修改,保持默认会比较简单些。
    一路next到下一步的界面时,在Search栏目里输入“qgis”,可以查询到QGis的相关资源。其中”ltr”的版本表示long time release, 是比较稳定的发布版本。点击相应的库,使之由符号”n/a”变成一个打上叉的方框形状就表示选中相应的文件了,之后将会下载这个文件。
    我下载的是qgis-ltr
    在这里插入图片描述

    2.3下载完成后的说明

    目前先下载这一个包,如过后续出现什么问题那么继续再来这个页面下载,缺什么下载什么。

    3配置环境

    3.1建立.cmd文件

    建立一个.cmd文件,然后添加一些路径和环境变量(我也不知道为什么这么操作,只是看文档做,所以按自己理解来做一些改变。)然后把下边的复制粘贴进去,双击该.cmd文件,可以任意命名,可以放在任何位置都行,我命名为pyqgis.cmd。(可能我添加的path有点多,主要后边试环境,一直出错,所以加了许多Path,有可能是用不到的,但是环境已经配过来了,还是不要浪着改了。)

      @echo off
      SET OSGEO4W_ROOT=C:\OSGeo4W64
      call "%OSGEO4W_ROOT%"\bin\o4w_env.bat
      call "%OSGEO4W_ROOT%"\apps\grass\grass76\etc\env.bat
      @echo off
      path %PATH%;%OSGEO4W_ROOT%\apps\qgis-ltr\bin
      path %PATH%;%OSGEO4W_ROOT%\apps\grass\grass76\lib
      path %PATH%;C:\OSGeo4W64\apps\Qt5\bin
      path %PATH%;C:\OSGeo4W64\apps\Python37\Scripts
      path %PATH%;C:\OSGeo4W64\apps\Python27\Scripts
      path %PATH%;C:\OSGeo4W64\bin
      path %PATH%;C:\OSGeo4W64\apps\Python37\DLLs
      path %PATH%;C:\OSGeo4W64\apps\Python37\lib
      path %PATH%;C:\OSGeo4W64\apps\Python37\lib\site-packages
      path %PATH%;C:\OSGeo4W64\apps\qgis-ltr\bin
      path %PATH%;C:\OSGeo4W64\apps\qgis-ltr\python
      path %PATH%;C:\OSGeo4W64\apps\qgis-ltr\python\qgis
      path %PATH%;C:\OSGeo4W64\apps\Qt5
      path %PATH%;C:\OSGeo4W64\apps\qgis-ltr\qtplugins
      path %PATH%;C:\OSGeo4W64\apps\qgis-ltr\python\PyQt5
    
      set PYTHONPATH=%PYTHONPATH%;%OSGEO4W_ROOT%\apps\qgis-ltr\python
      set PYTHONHOME=%OSGEO4W_ROOT%\apps\Python37
      
      set PATH=C:\Program Files;%PATH%
       cmd.exe
    

    3.2双击pyqgis.cmd文件

    在弹出的cmd命令框中,输入python3,然后分别输入
    >>> import qgis.core
    >>> import PyQt5.QtCore
    如果没有异常,那此步骤就可以结束。
    但是怎么可能没有问题,如果真这么按教程来就好了。
    下边仅就我遇到的问题进行说明。

    3.2.1问题1

    具体是什么报错忘记了,也不能现在回去再让它再来报错一遍了,大概就是我运行pyqgis.cmd文件时出现找不到grass文件的意思,因为在pyqgis.cmd我配置的有call “%OSGEO4W_ROOT%”\apps\grass\grass76\etc\env.bat,它找不到该路径。我回到安装目录检查,确实没有该目录。那么就此回到osgeo4w安装界面进行安装grass,搜索grass,下载如下(keep的就是我下载过的):
    在这里插入图片描述
    然后继续双击pyqgis.cmd文件,在弹出的cmd命令框中,输入python3,然后分别输入
    >>> import qgis.core
    >>> import PyQt5.QtCore
    如果没有异常,那此步骤就可以结束。
    (此处我没有错误,如果各位有报错的话,报出缺什么东西,就回到osgeo4w安装界面进行安装相应部分就行)

    3.3安装pb_tool

    虽然我不知道这个东西给的什么,但是老外的配置文档上写了让安装那么就安装吧。
    双击pyqgis.cmd文件,在弹出的cmd命令框中,输入python3 -m pip install pb_tool
    ,如果输出如下:

    C:\Users\gsherman>pb_tool
        Usage: pb_tool [OPTIONS] COMMAND [ARGS]...
    
          Simple Python tool to compile and deploy a QGIS plugin. For help on a
          command use --help after the command: pb_tool deploy --help.
    
          pb_tool requires a configuration file (default: pb_tool.cfg) that declares
          the files and resources used in your plugin. Plugin Builder 2.6.0 creates
          a config file when you generate a new plugin template.
    
          See http://g-sherman.github.io/plugin_build_tool for for an example config
          file. You can also use the create command to generate a best-guess config
          file for an existing project, then tweak as needed.
    
          Bugs and enhancement requests, see:
          https://github.com/g-sherman/plugin_build_tool
    
        Options:
          --help  Show this message and exit.
    
        Commands:
          clean       Remove compiled resource and ui files
          clean_docs  Remove the built HTML help files from the...
          compile     Compile the resource and ui files
          config      Create a config file based on source files in...
          create      Create a new plugin in the current directory...
          dclean      Remove the deployed plugin from the...
          deploy      Deploy the plugin to QGIS plugin directory...
          doc         Build HTML version of the help files using...
          help        Open the pb_tools web page in your default...
          list        List the contents of the configuration file
          translate   Build translations using lrelease.
          update      Check for update to pb_tool
          validate    Check the pb_tool.cfg file for mandatory...
          version     Return the version of pb_tool and exit
          zip         Package the plugin into a zip file suitable...
    

    那么就是正常的,可以继续进行,以上内容时复制老外文档的,我的配置过去,不想搞了,大概就是这个样子如果安装成功,不报什么错误,就可以继续进行下去。
    但是我就比较惨了,老外成功,我继续报错(错误及解决方案如下)。

    3.3.1错误一

    错误信息:在C:\OSGeo4W64\apps\Python37\Scripts找不到pip
    大概就是这个意思(配置过去了,不太好截图之前的错误),那么我就去到该文件夹下,查看有pip没有,确实没有。那么回到osgeo4w安装界面进行安装python3-pip
    在这里插入图片描述

    3.3.2错误二

    安装完python3-pip后继续执行该步骤,报错信息如下:
    You are using pip version 19.0.3, however version 19.1.1 is available. You should consider upgrading via the ‘python -m pip install --upgrade pip’ command.
    该错误信息意思为所使用的pip版本太低,我们有的时19.0.3版本,但是需要的是19.1.1版本的。所以我们就需要对pip进行升级:在报错的cmd命令下输入
    python3 -m pip install --upgrade pip
    (记得一定是python3)
    然后继续安装pb_tool,至此我没有了报错信息。此步骤结束。

    3.4配置paycharm相关环境

    逛论坛时,看好多老外都说pycharm2019.1会出问题,我之前也用这个配不好,虽然不一定是pycharm2019.1的锅,但是以免万一还是不要用这一版本。
    我用了pycharm2018.3.4版本的。然后对我们之前生成的pyqgis.cmd进行里边内容的改写,当然你也可以新建立一个.cmd文件,具体内容如下:

     @echo off
      SET OSGEO4W_ROOT=C:\OSGeo4W64
      call "%OSGEO4W_ROOT%"\bin\o4w_env.bat
      call "%OSGEO4W_ROOT%"\apps\grass\grass76\etc\env.bat
      @echo off
      path %PATH%;%OSGEO4W_ROOT%\apps\qgis-ltr\bin
      path %PATH%;%OSGEO4W_ROOT%\apps\grass\grass76\lib
      path %PATH%;C:\OSGeo4W64\apps\Qt5\bin
      path %PATH%;C:\OSGeo4W64\apps\Python37\Scripts
      path %PATH%;C:\OSGeo4W64\apps\Python27\Scripts
      path %PATH%;C:\OSGeo4W64\bin
      path %PATH%;C:\OSGeo4W64\apps\Python37\DLLs
      path %PATH%;C:\OSGeo4W64\apps\Python37\lib
      path %PATH%;C:\OSGeo4W64\apps\Python37\lib\site-packages
      path %PATH%;C:\OSGeo4W64\apps\qgis-ltr\bin
      path %PATH%;C:\OSGeo4W64\apps\qgis-ltr\python
      path %PATH%;C:\OSGeo4W64\apps\qgis-ltr\python\qgis
      path %PATH%;C:\OSGeo4W64\apps\Qt5
      path %PATH%;C:\OSGeo4W64\apps\qgis-ltr\qtplugins
      path %PATH%;C:\OSGeo4W64\apps\qgis-ltr\python\PyQt5
    
      set PYTHONPATH=%PYTHONPATH%;%OSGEO4W_ROOT%\apps\qgis-ltr\python
      set PYTHONHOME=%OSGEO4W_ROOT%\apps\Python37
    
    
      set PATH=C:\Program Files;%PATH%
    
      start "PyCharm aware of Quantum GIS" /B "C:\Program Files\JetBrains\PyCharm Community Edition 2018.3.4\bin\pycharm64.exe"
    

    然后双击这个.cmd文件,便可以通过这个打开pycharm,然后对pycharm的python解释器进行配置,选择如下路径的python即可:
    在这里插入图片描述

    4代码测试

    运行如下代码:
    os.environ[‘QT_QPA_PLATFORM_PLUGIN_PATH’]=
    r’C:\OSGeo4W64\apps\Qt5\plugins’
    os.environ[‘PATH’] += r’;C:\OSGeo4W64\apps\qgis-ltr\bin;C:\OSGeo4W64\apps\Qt5\bin’
    这两行代码一定要加,不然会报出找不到qt插件的错误

    from qgis.core import *
    import os
    os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'C:\OSGeo4W64\apps\Qt5\plugins'
    os.environ['PATH'] += r';C:\OSGeo4W64\apps\qgis-ltr\bin;C:\OSGeo4W64\apps\Qt5\bin'
    # supply path to qgis install location
    QgsApplication.setPrefixPath("C:\OSGeo4W64", True)
    
    # create a reference to the QgsApplication, setting the second argument to False disables the GUI
    qgs = QgsApplication([], False)
    
    # load providers
    qgs.initQgis()
    # Write your code here to load some layers, use processing , algorithms, etc.
    
    my_project = QgsProject()
    my_project.write(r"D:\my_pro.qgs")
    
    my_pro = QgsProject()
    my_pro.read(r"D:\my_pro.qgs")
    print(my_pro.fileName())
    
    
    # When your script is complete, call exitQgis() to remove the
    # provider and layer registries from memory
    qgs.exitQgis()
    

    该代码是创建一个qgis工程,然后读取该工程,输出该工程的名字。运行结果如下:
    在这里插入图片描述
    在d盘该工程也创建成功。
    在这里插入图片描述

    5总结

    为什么配置一个pyqgis的环境花费了这么久?可能确实国内qgis用的不是很多,pyqgis少之更少。官方给的文档配置环境仅两句话,根本没有什么用。百度出来的博客写的内容不是很详细,而且都是老版本的qgis。新版本的qgis变化还是挺大的,作为一个新手却只能照着博客写的教程,来一步步操作,一报错就不知道怎么做了,就开始怀疑自己从开始装的软件对不对,卸了装,装了卸,尝试各种版本,时间都花费到这里了。
    最后还是心态放正,不急,耐心在谷歌看一些英文的论坛,找到了几篇优质文档,按照文档一步一步操作,但还是报了各种错误,最后按照自己的理解给解决了。
    总结就是,尽信教程不如半信教程,每个人的环境都不一样,别人不会报错,但自己就会报错,要学会去看错误信息,根据错误信息去解决问题,不要教程上没有自己的报错信息就无法解决。

    6参考文档

    1.Quick Guide to Getting Started with PyQGIS 3 on Windows
    http://spatialgalaxy.net/2018/02/13/quick-guide-to-getting-started-with-pyqgis3-on-windows/
    2.Error from create a reference to the QgsApplication
    https://gis.stackexchange.com/questions/302774/error-from-create-a-reference-to-the-qgsapplication

    展开全文
  • PyQGIS developer cookbook

    2015-03-06 11:30:51
    描绘怎么利用python 语言对QGIS进行二次开发,是一本很好的参考书籍。
  • pyqgis 图层管理

    2020-08-13 22:00:41
    导入必要的对象 from qgis.core import ( QgsLayerTreeModel ) from qgis.gui import ( QgsLayerTreeView, QgsLayerTreeMapCanvasBridge ) 创建停靠面板 def create_dockwidget(self,widget): ...

    导入必要的对象

     from qgis.core import (
        QgsLayerTreeModel
    )
    from qgis.gui import (
        
        QgsLayerTreeView,
        QgsLayerTreeMapCanvasBridge
    )
    

    创建停靠面板

     def create_dockwidget(self,widget):
            """创建停靠图层控件"""
            dock=QDockWidget("图层")
            dock.setWidget(widget)
            dock.setObjectName("图层")
            dock.setFeatures(dock.DockWidgetFloatable|dock.DockWidgetMovable)
            self.addDockWidget(Qt.LeftDockWidgetArea,dock)
    

    初始化图层面板视图

    def initLayerTreeView(self):
            """
            初始化图层树视图
            """
            root=QgsProject.instance().layerTreeRoot()
            self.lyrTreeModel=QgsLayerTreeModel(root)
            self.lyrTreeModel.setFlag(QgsLayerTreeModel.AllowNodeRename)
            self.lyrTreeModel.setFlag(QgsLayerTreeModel.AllowNodeReorder)
            self.lyrTreeModel.setFlag(QgsLayerTreeModel.AllowNodeChangeVisibility)
            self.lyrTreeModel.setFlag(QgsLayerTreeModel.ShowLegendAsTree)
            self.lyrTreeModel.setAutoCollapseLegendNodes(10)
            
            self.lyrTreeView=QgsLayerTreeView()
            self.lyrTreeView.setModel(self.lyrTreeModel)
            self.lyrTreeCavasBridge=QgsLayerTreeMapCanvasBridge(root,self._canvas)
            self.create_dockwidget(self.lyrTreeView)
    

    完整代码

    import sys
    import os
    from qgis.PyQt.QtCore import (
        Qt
        )
    from qgis.PyQt.QtGui import (
        QIcon
        )
    from qgis.PyQt.QtWidgets import(
        QMainWindow,
        QVBoxLayout,
        QWidget,
        QFileDialog,
        QAction,
        QDockWidget
        )
    from qgis.core import (
        QgsApplication,
        QgsVectorLayer,
        QgsRasterLayer,
        QgsProject,
        QgsLayerTreeModel
    )
    from qgis.gui import (
        QgsMapCanvas,
        QgsMapTool,
        QgsLayerTreeView,
        QgsLayerTreeMapCanvasBridge
    )
    
    class PanTool(QgsMapTool):
        def __init__(self,mapCanvas):
            super(PanTool,self).__init__(mapCanvas)
            self.setCursor(Qt.OpenHandCursor) 
            self.dragging=False
    
        def canvasMoveEvent(self,event):
            if event.buttons() == Qt.LeftButton:
                if not self.dragging:
                    self.dragging=True
                    self.canvas().panAction(event)
    
        def canvasReleaseEvent(self,event):
            if event.button()== Qt.LeftButton and self.dragging:
                self.canvas().panActionEnd(event.pos())
                self.dragging=False
    
    class MapViewer(QMainWindow):
        def __init__(self):
            super(MapViewer,self).__init__()
            self.setWindowTitle("Map Viewer")
            self.setWindowIcon(QIcon("images/qgis-icon.png"))
            self._layers=[]
    
            self.create_widget()
            self.setup_file_menu()
    
        def create_dockwidget(self,widget):
            """创建停靠图层控件"""
            dock=QDockWidget("图层")
            dock.setWidget(widget)
            dock.setObjectName("图层")
            dock.setFeatures(dock.DockWidgetFloatable|dock.DockWidgetMovable)
            self.addDockWidget(Qt.LeftDockWidgetArea,dock)
    
        def create_widget(self):
            """
            创建布局
            """
            self._canvas =QgsMapCanvas()
            self._canvas.setCanvasColor(Qt.white)
            self._canvas.show()
    
            layout=QVBoxLayout()
            layout.addWidget(self._canvas)
    
            contents=QWidget()
            contents.setLayout(layout)
            self.setCentralWidget(contents)
            self.initLayerTreeView()
            
    
        def initLayerTreeView(self):
            """
            初始化图层树视图
            """
            root=QgsProject.instance().layerTreeRoot()
            self.lyrTreeModel=QgsLayerTreeModel(root)
            self.lyrTreeModel.setFlag(QgsLayerTreeModel.AllowNodeRename)
            self.lyrTreeModel.setFlag(QgsLayerTreeModel.AllowNodeReorder)
            self.lyrTreeModel.setFlag(QgsLayerTreeModel.AllowNodeChangeVisibility)
            self.lyrTreeModel.setFlag(QgsLayerTreeModel.ShowLegendAsTree)
            self.lyrTreeModel.setAutoCollapseLegendNodes(10)
            
            self.lyrTreeView=QgsLayerTreeView()
            self.lyrTreeView.setModel(self.lyrTreeModel)
            self.lyrTreeCavasBridge=QgsLayerTreeMapCanvasBridge(root,self._canvas)
            self.create_dockwidget(self.lyrTreeView)
    
    
        def setup_file_menu(self):
            """
            创建菜单和工具栏
            """
            file_menu=self.menuBar().addMenu("文件")
            view_menu=self.menuBar().addMenu("视图")
            mode_menu=self.menuBar().addMenu("Mode")
    
            open_shpfile_action=self.create_action("打开shp",self.open_shpfile)
            open_rasterfile_action=self.create_action("打开tif",self.open_rasterfile)
            toolbar_=self.addToolBar("tools")
            zoomIn_action=self.create_action("ZoomIn",self.zoomIn,None,'images/mActionZoomIn.svg',"ZoomIn")
            zoomOut_action=self.create_action("ZoomOut",self.zoomOut,None,'images/mActionZoomOut.svg',"ZoomOut")
            
            self.pan_action=self.create_action("Pan",self.setPanMode,None,'images/mActionPan.svg',"Pan",True)
            self.panTool=PanTool(self._canvas)
            self.panTool.setAction(self.pan_action)
            
            self.add_action(file_menu,(open_shpfile_action,open_rasterfile_action,None))
            self.add_action(toolbar_,(zoomIn_action,zoomOut_action,self.pan_action))
    
        def open_shpfile(self):
            """打开shp文件"""
            filename,_=QFileDialog.getOpenFileName(self,'open shp file','.','(*.shp)')
            if filename:
                basename=os.path.basename(filename)
                lyrname=os.path.splitext(basename)[0]
                layer=QgsVectorLayer(filename,lyrname,"ogr")
                if not layer.isValid():
                    raise IOError("Invalid shapefile")
                QgsProject.instance().addMapLayer(layer)
                self._layers.append(layer)
                self._canvas.setExtent(layer.extent())
                self._canvas.setLayers(self._layers)
        
        def open_rasterfile(self):
            """打开tif文件"""
            filename,_=QFileDialog.getOpenFileName(self,'open raster file','.','(*.tif)')
            if filename:
                basename=os.path.basename(filename)
                lyrname=os.path.splitext(basename)[0]
                layer=QgsRasterLayer(filename,lyrname)
                if not layer.isValid():
                    raise IOError("Invalid shapefile")
                QgsProject.instance().addMapLayer(layer)
                self._layers.append(layer)
                self._canvas.setExtent(layer.extent())
                self._canvas.setLayers(self._layers)
    
        def create_action(self,text,slot=None,shotcut=None,icon=None,tip=None,checkable=False,signal='triggered'): 
            """
            创建QAction
            """
            action=QAction(text,self) 
            if icon is not None: 
                action.setIcon(QIcon(icon)) 
            if shotcut is not None: 
                action.setShortcut(shotcut) 
            if tip is not None: 
                action.setToolTip(tip) 
                action.setStatusTip(tip) 
            if slot is not None: 
                getattr(action,signal).connect(slot) 
            if checkable: 
                action.setCheckable(True) 
            return action 
        
        def add_action(self,target,actions):
            """
            menu and action
            """
            for action in actions:
                if action is None:
                    target.addSeparator()
                else:
                    target.addAction(action)
    
        def zoomIn(self):
            '''
            放大
            '''
            self._canvas.zoomIn()
        def zoomOut(self):
            """
            缩小
            """
            self._canvas.zoomOut()
            
        def setPanMode(self):
            """
            平移
            """
    
            self.pan_action.setChecked(True)
            self._canvas.setMapTool(self.panTool)
                
    
        def setExploreMode(self):
            """
            查询
            """
            pass
    
    if __name__=="__main__":
        
        QgsApplication.setPrefixPath("qgis",True)
        qgs=QgsApplication([],True)
        qgs.initQgis()
    
        viewer=MapViewer()
        viewer.show()
        exitCode=qgs.exec()
        qgs.exitQgis()
    

    效果

    res

    展开全文
  • PyQGIS 开发中,图层渲染有一套强大的 API 体系,本文就向大家介绍一些常用的图层渲染方法,帮助大家开发自己的专题图软件。这件事非常重要,再次强调:以下内容完全可以照搬到 QGIS C++ 开发环境中!!!由于图层...
  • PYQGIS——图层管理器

    千次阅读 2019-12-12 14:57:10
    PYQGIS——图层管理器 界面设计 写代码 程序入口 if __name__ == '__main__': # 应用入口,使用GUI qgs = QgsApplication([], True) # 设置,qgis安装路径,这里写相对路径,如果是源码运行,这行可不写 qgs....
  • pyqgis 加载栅格图层

    2020-07-31 10:54:52
    import os from qgis.core import ( QgsRasterLayer, QgsProject, QgsApplication ) from qgis.gui import( QgsMapCanvas ) os.environ['GDAL_DATA'] = r'C:\OSGeo4W\share\gdal' os.environ['PROJ_LIB'] = r'C:...
  • pyqgis 加载矢量图层

    2020-07-31 10:53:00
    import os from qgis.core import ( QgsVectorLayer, QgsProject, QgsApplication ) from qgis.gui import( QgsMapCanvas ) os.environ['GDAL_DATA'] = r'C:\OSGeo4W\share\gdal' os.environ['PROJ_LIB'] = r'C:...
  • PyQGIS开发者手册-3 加载图层

    千次阅读 2019-07-06 12:48:05
    3 加载图层 目录 ...import os # pyqgis控制台同样需要 from qgis.core import ( QgsVectorLayer ) 让我们用数据打开一些图层。QGIS可识别矢量和栅格图层。此外,自定义图层类型也可以使用,...
  • pyqgis 绘制几何体

    2020-07-31 14:32:42
    import os from qgis.PyQt.QtGui import QColor from qgis.core import ( QgsProject, QgsApplication, QgsPoint, QgsPointXY, QgsGeometry, QgsRectangle ) from qgis.gui import( QgsMapCanvas, ...os.e
  • 配置pyqgis+pycharm开发环境 前言 最近导师要求做一个桌面端程序,本来打算使用python+pyqgis(运行在pyqt5之上)这一套方案,后来老师又拍脑(pi)袋(gu)决定做BS的架构。虽然不使用了此套方案,但考虑到pyqgis的开发...
  • PyQGIS速查表

    2020-04-01 10:29:52
    用户接口 改变外观 from qgis.PyQt.QtWidgets import QApplication app = QApplication.instance() qss_file = open(r"/path/to/style/file.qss").read() app.setStyleSheet(qss_file) 改变图标和标题 ...
  • pyqgis 单波段着色

    2021-06-18 23:50:52
    from qgis.core import ( QgsRasterLayer, QgsProject, QgsPointXY, QgsRaster, QgsRasterShader, QgsColorRampShader, QgsSingleBandPseudoColorRenderer, QgsSingleBandColorDataRenderer, ...
  • PyQGIS Developer CookBook

    2012-11-08 12:47:25
    PyQGIS Developer CookBook》高清版 PDF,由 Martin Dobias 亲自执笔,是 QGIS 二次开发方面少有的绝佳资料···
  • PyQGIS开发 -- 环境搭建

    千次阅读 2017-08-08 15:20:27
    本文包含基本的 PyQGIS 开发环境配置,详细描述如何使用Eclipse + PyDev搭建PyQGIS插件开发的调试环境。
  • PyQGIS开发者手册-8 使用地图画布

    千次阅读 2019-08-10 12:40:43
    8 使用地图画布 目录 8 使用地图画布 ...地图画布控件可能是QGIS中最重要的控件,因为它显示了由重叠的地图图层组成的地图,并允许与地图和图层进行交互。...与其他图形程序类似,总有一...PyQGIS开发者手册-完整版 ...
  • PyQGIS开发 -- 离线地图

    2020-12-22 05:10:56
    PyQGIS示例 操作并不复杂,接下来我们使用PyQGIS来完成离线地图数据加载的操作。 同样,我们用加载QGIS工程文件的方式来达到打开离线地图数据的目的,代码如下: from PyQt4.QtCore import * dir = "/Users/Jacory/...
  • PYQGIS——图层目录树右键菜单一文中我们实现了怎么添加图层目录树的上下文菜单,我们来添加一个open Attribute Table菜单代码片段如下: ... layer = self.layerTreeView.currentLayer() if layer.type() == ...
  • 自定义窗口类加载显示地图 import sys from qgis.PyQt.QtCore import Qt from qgis.PyQt.QtWidgets import QMainWindow,QVBoxLayout,QWidget from qgis.core import ( QgsApplication, QgsVectorLayer, ...
  • pyqgis 打印日志

    2020-07-31 14:50:37
    import os from qgis.PyQt.QtWidgets import QAction,QMainWindow from qgis.PyQt.QtCore import Qt from qgis.PyQt.QtGui import QColor from qgis.core import ( QgsProject, QgsApplication, ...
  • import sys from qgis.PyQt.QtCore import Qt from qgis.PyQt.QtGui import QIcon from qgis.PyQt.QtWidgets import( QMainWindow, QVBoxLayout, QWidget, QFileDialog, QAction ) from qgis.core import ( ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 397
精华内容 158
关键字:

pyqgis