Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance qgis view & macros #426

Merged
merged 9 commits into from
Aug 5, 2024
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -352,19 +352,27 @@ Des vecteurs externes *.shp* et *.gpkg* peuvent être intégrés à la vue en in

Dans le cas où l'on veut avoir une emprise pour la vue (emprise de travail) plus petite que l'emprise du chantier (emprise du cache), elle est à indiquer avec **--bbox** Xmin Ymin Xmax Ymax.

Pour intégrer un fichier de macros QGIS à la vue, il faut indiquer le chemin vers le fichier macros prototype avec **-m**. Ce fichier sera adapté au chantier avant d'être intégré à la vue, en remplaçant les clés `__IDBRANCH__`, `__URLSERVER__` et `__TILEMATRIXSET__` avec les valeurs correspondantes pour le chantier - exemple :
Pour intégrer un fichier de macros QGIS à la vue, il faut indiquer le chemin vers le fichier macros prototype avec **-m**. Ce fichier sera adapté au chantier avant d'être intégré à la vue, en remplaçant les clés `__IDBRANCH__`, `__URLSERVER__`, `__TILEMATRIXSET__`, `__STYLE__`, `__CRS__`, `__PIXELSIZEX__`, `__PIXELSIZEY__` avec les valeurs correspondantes pour le chantier - exemple :

- Extrait prototype macros, avant adaptation :
```
id_branch = __IDBRANCH__
url_server = __URLSERVER__
tile_matrix_set = __TILEMATRIXSET__
style = __STYLE__
crs = __CRS__
pixel_size_x = __PIXELSIZEX__
pixel_size_y = __PIXELSIZEY__
```
- Extrait macros, après adaptation :
```
id_branch = '32'
url_server = 'http://localhost:8081/'
tile_matrix_set = 'LAMB93_20cm'
style = 'RVB'
crs = '2154'
pixel_size_x = 0.2
pixel_size_y = 0.2
```

Un exemple de fichier macros prototype est fourni dans le dossier *ressources*.
Expand Down
10 changes: 7 additions & 3 deletions ressources/example_macros_qgis.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,18 @@ def closeProject():
id_branch = __IDBRANCH__
url_server = __URLSERVER__
tile_matrix_set = __TILEMATRIXSET__
style = __STYLE__
crs = __CRS__
pixel_size_x = __PIXELSIZEX__
pixel_size_y = __PIXELSIZEY__
# ===================================

url_graph = url_server + id_branch + '/graph'
url_patch = url_server + id_branch + '/patch'
url_undo = url_server + id_branch + '/patch/undo'
url_redo = url_server + id_branch + '/patch/redo'
url_wmts = url_server + id_branch + '/wmts'
source='contextualWMSLegend=0&crs=EPSG:2154&dpiMode=7&featureCount=10&format=image/png&layers=opi&styles=RVB&tileDimensions=Name%3DXXX&tileMatrixSet='+tile_matrix_set+'&url='+url_wmts+'?SERVICE%3DWMTS%26REQUEST%3DGetCapabilities%26VERSION%3D1.0.0'
source='contextualWMSLegend=0&crs=EPSG:'+crs+'&dpiMode=7&featureCount=10&format=image/png&layers=opi&styles='+style+'&tileDimensions=Name%3DXXX&tileMatrixSet='+tile_matrix_set+'&url='+url_wmts+'?SERVICE%3DWMTS%26REQUEST%3DGetCapabilities%26VERSION%3D1.0.0'
OPI=None
color=None
opi_layer = None
Expand Down Expand Up @@ -81,7 +85,7 @@ def sendPatch(feature, OPI, color):
exporter = QgsJsonExporter()
patch = json.loads(exporter.exportFeatures([feature]))
# print(patch)
patch['crs'] = {'type': 'name', 'properties': {'name': 'urn:ogc:def:crs:EPSG::2154'}}
patch['crs'] = {'type': 'name', 'properties': {'name': 'urn:ogc:def:crs:EPSG::'+crs}}
patch['features'][0]['properties'] = {'color': color, 'opiName': OPI}
res = requests.post(url_patch, json=patch)
return res.text
Expand Down Expand Up @@ -295,7 +299,7 @@ def on_key(event):

chem_export_txt = os.path.join(rep_pont, nom_export.replace('.tif', '.txt'))

cmd = f'gdalwarp -tr 0.05 0.05 -tap -r near -co TFW=YES {ortho_layer.source()} {chem_export}\
cmd = f'gdalwarp -tr {pixel_size_x} {pixel_size_y} -tap -r near -co TFW=YES {ortho_layer.source()} {chem_export}\
-cutline {src_poly} -csql "select ret.geom from retouches_info as ret where ret.fid == {id_poly}"\
-crop_to_cutline -overwrite -dstnodata 0'
os.popen(cmd).readlines()
Expand Down
2 changes: 2 additions & 0 deletions scripts/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

import cache_def as cache

# enable gdal/ogr exceptions
gdal.UseExceptions()

cpu_dispo = multiprocessing.cpu_count()

Expand Down
3 changes: 3 additions & 0 deletions scripts/cache_def.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
from numpy import base_repr
from osgeo import gdal

# enable gdal/ogr exceptions
gdal.UseExceptions()

COG_DRIVER = gdal.GetDriverByName('COG')


Expand Down
45 changes: 38 additions & 7 deletions scripts/create_qgis_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,9 @@ def read_args():
help='cache id',
type=int)
parser.add_argument('-b', '--branch_name',
help="name of new branch to be created on cache (default: newBranch)",
type=str, default='newBranch')
help="name of new branch to be created on cache",
required=True,
type=str)
parser.add_argument('-s', '--style_ortho',
help="style for ortho to be exported to xml (default: RVB)",
type=str, default='RVB', choices=['RVB', 'IR', 'IRC'])
Expand Down Expand Up @@ -95,6 +96,19 @@ def suppress_cachetag(xml_in, xml_out):
print(f"File '{xml_out}' written")


def set_nb_bands(xml_in, xml_out, nb_bands):
""" Set number of bands or channels in xml file """
if nb_bands is None or nb_bands < 0:
raise SystemExit(f'ERROR: Bad number of bands (={nb_bands})')
tree_xml = etree.parse(xml_in)
root_xml = tree_xml.getroot()
bands_count = root_xml.find('BandsCount')
if bands_count is None:
raise SystemExit(f"ERROR: 'BandsCount' tag not found in '{xml_in}'")
bands_count.text = str(nb_bands)
tree_xml.write(xml_out)


def set_extent_xml(xml_in, xml_out, extent_xmin, extent_ymin, extent_xmax, extent_ymax):
""" Set extent limits in an xml file """
tree_xml = etree.parse(xml_in)
Expand All @@ -116,10 +130,11 @@ def set_extent_xml(xml_in, xml_out, extent_xmin, extent_ymin, extent_xmax, exten
print(f"File '{xml_out}' written")


def modify_xml(xml_in, xml_out, extent_xmin=None, extent_ymin=None,
def modify_xml(xml_in, xml_out, nb_bands, extent_xmin=None, extent_ymin=None,
extent_xmax=None, extent_ymax=None):
""" Suppress cache tag and set extent in an xml file """
""" Suppress cache tag and set number of bands & extent in an xml file """
suppress_cachetag(xml_in, xml_out)
set_nb_bands(xml_out, xml_out, nb_bands)
if extent_xmin and extent_ymin and extent_xmax and extent_ymax:
set_extent_xml(xml_out, xml_out, extent_xmin, extent_ymin, extent_xmax, extent_ymax)
print(f"File '{xml_out}' written")
Expand Down Expand Up @@ -230,8 +245,12 @@ def print_info_add_layer(layer_name):
# suppress Cache tag and set extent
xml_ortho = os.path.join(dirpath_out, 'ortho.xml')
xml_graph = os.path.join(dirpath_out, 'graphe_surface.xml')
modify_xml(xml_ortho_tmp, xml_ortho, bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax)
modify_xml(xml_graph_tmp, xml_graph, bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax)
# get number of channels or bands for ortho layer
nb_bands_from_style = {'RVB': 3, 'IR': 1, 'IRC': 3}
nb_bands_ortho = nb_bands_from_style.get(ARG.style_ortho)
modify_xml(xml_ortho_tmp, xml_ortho, nb_bands_ortho, bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax)
# graph layer is a RGB layer (3 channels)
modify_xml(xml_graph_tmp, xml_graph, 3, bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax)
# TODO: suppress xml ortho_tmp and graph_tmp - for now, useful for comparison

# --------- create contours vrt from graph.xml -----------
Expand Down Expand Up @@ -268,7 +287,12 @@ def print_info_add_layer(layer_name):
ch = etree.SubElement(mdata, 'MDI', attrib={'key': key})
ch.text = val
# add children tags ComplexSource for band 2 and 3
if rband.find('ComplexSource') is None and rband.find('SimpleSource') is None:
raise SystemExit(f"ERROR: Neither 'ComplexSource' tag, nor 'SimpleSource' \
could be found in '{vrt_tmp}' file")
complsrc = rband.find('ComplexSource')
if complsrc is None and rband.find('SimpleSource') is not None:
complsrc = rband.find('SimpleSource')
for i in range(2, 4):
tmp = deepcopy(complsrc)
srcband = tmp.find('SourceBand')
Expand Down Expand Up @@ -320,6 +344,9 @@ def color_to_contour(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, rast
# add to group
ortho_group.insertChildNode(1, QgsLayerTreeLayer(ortho_layer))
print_info_add_layer(ortho_lname)
# get pixel size from layer
pixel_size_x = round(ortho_layer.rasterUnitsPerPixelX(), 4)
pixel_size_y = round(ortho_layer.rasterUnitsPerPixelY(), 4)
# get crs from layer
crs = ortho_layer.crs()
# set project crs
Expand Down Expand Up @@ -467,7 +494,11 @@ def color_to_contour(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, rast
# adapt macros to working data
words_to_replace = {'__IDBRANCH__': branch_id,
'__URLSERVER__': ARG.url+'/',
'__TILEMATRIXSET__': tms}
'__TILEMATRIXSET__': tms,
'__STYLE__': ARG.style_ortho,
'__CRS__': crs.postgisSrid(),
'__PIXELSIZEX__': pixel_size_x,
'__PIXELSIZEY__': pixel_size_y}
words_not_found = []
with open(ARG.macros, 'r', encoding='utf-8') as file_macro_in:
macros_data = file_macro_in.read()
Expand Down
Loading