import os def parse_colormap_file(fn, filter=None): labels = [] colors = [] class_names = [] with open(fn, 'r') as f: for l in f.read().splitlines(): sl = l.split(' ') if filter is not None and int(sl[0]) not in filter: continue labels.append(int(sl[0])) colors.append((int(sl[1]),int(sl[2]),int(sl[3]),int(sl[4]))) class_names.append(' '.join(sl[5:])) z = sorted(zip(labels,class_names,colors)) labels = [x[0] for x in z] class_names = [x[1] for x in z] colors = [x[2] for x in z] return labels, class_names, colors def create_qgs_style(map, palette): labels, class_names, colors = parse_colormap_file(palette) out_str_pre = """<!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'> <qgis hasScaleBasedVisibilityFlag="0" maxScale="0" styleCategories="AllStyleCategories" minScale="1e+8" version="3.16.3-Hannover"> <flags> <Identifiable>1</Identifiable> <Removable>1</Removable> <Searchable>1</Searchable> </flags> <temporal mode="0" enabled="0" fetchMode="0"> <fixedRange> <start></start> <end></end> </fixedRange> </temporal> <customproperties> <property key="WMSBackgroundLayer" value="false"/> <property key="WMSPublishDataSourceUrl" value="false"/> <property key="embeddedWidgets/count" value="0"/> <property key="identify/format" value="Value"/> </customproperties> <pipe> <provider> <resampling zoomedInResamplingMethod="nearestNeighbour" zoomedOutResamplingMethod="nearestNeighbour" enabled="false" maxOversampling="2"/> </provider> <rasterrenderer alphaBand="-1" opacity="1" nodataColor="" band="1" type="paletted"> <rasterTransparency/> <minMaxOrigin> <limits>None</limits> <extent>WholeRaster</extent> <statAccuracy>Estimated</statAccuracy> <cumulativeCutLower>0.02</cumulativeCutLower> <cumulativeCutUpper>0.98</cumulativeCutUpper> <stdDevFactor>2</stdDevFactor> </minMaxOrigin> <colorPalette> """ out_str_post=""" </colorPalette> <colorramp name="[source]" type="randomcolors"/> </rasterrenderer> <brightnesscontrast contrast="0" brightness="0" gamma="1"/> <huesaturation saturation="0" colorizeBlue="128" colorizeStrength="100" colorizeRed="255" colorizeOn="0" colorizeGreen="128" grayscaleMode="0"/> <rasterresampler maxOversampling="2"/> <resamplingStage>resamplingFilter</resamplingStage> </pipe> <blendMode>0</blendMode> </qgis> """ out_str_colors = '\n'.join([' <paletteEntry alpha="255" value="{}" label="{}" color="#{:02x}{:02x}{:02x}"/>'.format(l,cn,c[0],c[1],c[2]) for l,cn,c in zip(labels, class_names, colors)]) out_fn = os.path.splitext(map)[0] + '.qml' with open(out_fn, 'w') as f: f.write(out_str_pre) f.write(out_str_colors) f.write(out_str_post) return