def read_talos_palette(s: str) -> ColorPalette: res = ColorPalette() x = s.split(';') min_value = num(x[0]) count = int(x[1]) selected = x[2] lock_values = x[3] multiplier = num(x[4]) special_draw = x[5] interpolate = x[6] log_base = num(x[8]) if log_base == 0: ln_log_base = None else: ln_log_base = math.log(log_base) j = 8 for i in range(count): name = x[j] color = x[j+2] color = res.pas_color_to_rgb(color) brush = x[j+3] key = min_value + i * multiplier if ln_log_base: key = math.exp(ln_log_base * key) # == log_base^key res.pal[key] = color j += 4 # flags = x[j] # pal_version = x[j+1] return res
def read_file_txt(self, filename: Optional[PathLikeOrStr] = None, lines: Optional[Sequence[str]] = None): """ Read GDAL Text-based color configuration file """ if filename is not None: lines = open(filename).readlines() if not isinstance(lines, Sequence): raise Exception('unknown input {}'.format(lines)) self.pal.clear() for line in lines: split_line = line.strip().split(' ', 1) if len(split_line) < 2: continue try: color = self.pal_color_to_rgb(split_line[1]) key = split_line[0].strip() except: raise Exception('Error reading palette line: {}'.format(line)) try: key = base.num(key) except ValueError: if key.lower() in self.ndv_keys: self.ndv = color continue else: # maybe percent self._all_numeric = False self.pal[key] = color
def apply_percent(self, min_val: Real, max_val: Real): if min_val is None or max_val is None: raise Exception('no min or max values to apply') if self._all_numeric: # nothing to do return all_numeric = True new_pal = self.pal.copy() for num in self.pal.keys(): if not isinstance(num, str): continue is_percent = num.endswith('%') if is_percent: new_num = num.rstrip('%') try: new_num = base.num(new_num) if is_percent: new_num = (max_val - min_val) * new_num * 0.01 + min_val new_pal[new_num] = new_pal.pop(num) except ValueError: all_numeric = False else: all_numeric = False continue if all_numeric: self._all_numeric = True self.pal = new_pal
def read_xml(self, xml_filename, type=None, tag_name=None): if tag_name is None: if type is None: type = base.get_suffix(xml_filename) type = type.lstrip('.').lower() if type == 'qlr': # <paletteEntry color="#ffffff" alpha="0" label="0" value="0"/> tag_name = "paletteEntry" elif type == 'qml': # <item label="-373" color="#d7191c" alpha="255" value="-373"/> tag_name = "item" else: raise Exception('Unknown file type {}'.format(xml_filename)) self.pal.clear() qlr = minidom.parse(str(xml_filename)) # <paletteEntry color="#ffffff" alpha="0" label="0" value="0"/> color_palette = qlr.getElementsByTagName(tag_name) for palette_entry in color_palette: color = palette_entry.getAttribute("color") if str(color).startswith('#'): color = int(color[1:], 16) alpha = palette_entry.getAttribute("alpha") alpha = int(alpha) color = color + (alpha << 8 * 3) # * 256**3 key = palette_entry.getAttribute("value") key = base.num(key) self.pal[key] = color
def read_color_file(self, color_filename_or_lines: Optional[Union[PathLikeOrStr, 'ColorPalette', Sequence]]): if isinstance(color_filename_or_lines, ColorPalette): return self elif color_filename_or_lines is None: self.pal.clear() return self elif base.is_path_like(color_filename_or_lines): color_filename_or_lines = open(color_filename_or_lines).readlines() elif not isinstance(color_filename_or_lines, Sequence): raise Exception('unknown input {}'.format(color_filename_or_lines)) self.pal.clear() for line in color_filename_or_lines: split_line = line.strip().split(' ', 1) if len(split_line) < 2: continue try: color = self.pal_color_to_rgb(split_line[1]) key = split_line[0].strip() except: raise Exception('Error reading palette line: {}'.format(line)) try: key = base.num(key) except ValueError: # should be percent self._all_numeric = False pass self.pal[key] = color
def read_file_qml(self, qml_filename: PathLikeOrStr, tag_name=None, type=None): """ Read QGIS Layer Style File (qml) or QGIS Layer Definition File (qlr) """ qlr = minidom.parse(str(qml_filename)) if tag_name is None: if type is None: renderer = qlr.getElementsByTagName('rasterrenderer') if renderer is None: raise Exception(f'Cannot find "rasterrenderer" in {qml_filename}') type = renderer[0].getAttribute("type") type_to_tag_name = { # <rasterrenderer type="paletted" opacity="1" alphaBand="-1" band="1" nodataColor=""> # <paletteEntry color="#ffffff" alpha="0" label="0" value="0"/> "paletted": "paletteEntry", # <rasterrenderer type="singlebandpseudocolor" opacity="1" alphaBand="-1" band="1" classificationMax="100" classificationMin="0" nodataColor=""> # <item label="-373" color="#d7191c" alpha="255" value="-373"/> "singlebandpseudocolor": "item", } if type not in type_to_tag_name: raise Exception(f'Unknown type: {type} in {qml_filename}') tag_name = type_to_tag_name[type] self.pal.clear() color_palette = qlr.getElementsByTagName(tag_name) for palette_entry in color_palette: color = palette_entry.getAttribute("color") if str(color).startswith('#'): color = int(color[1:], 16) alpha = palette_entry.getAttribute("alpha") alpha = int(alpha) color = color + (alpha << 24) key = palette_entry.getAttribute("value") key = base.num(key) self.pal[key] = color
def test_utils_py_0(): for b in (False, 'False', 'OfF', 'no'): assert not base.is_true(b) for b in (True, 'TruE', 'ON', 'yes'): assert base.is_true(b) assert base.enum_to_str(Extent.UNION) == 'UNION' assert base.enum_to_str('UNION') == 'UNION' filename = Path('abc') / Path('def') / Path('a.txt') assert base.is_path_like(Path(filename)) assert base.is_path_like(str(filename)) assert not base.is_path_like(None) assert not base.is_path_like([filename]) assert base.get_suffix(filename) == '.txt' assert base.get_extension(filename) == 'txt' for idx, b in enumerate((0x23, 0xc1, 0xab, 0x00)): byte = base.get_byte(0xab_c1_23, idx) assert byte == b assert base.path_join(filename, 'a', 'b') == str(filename / 'a' / 'b') assert base.num(42) == 42 assert base.num('42') == 42 assert isinstance(base.num('42'), int) assert base.num(42.0) == 42.0 assert base.num('42.0') == 42.0 assert isinstance(base.num('42.0'), float) assert base.num('42.') == 42.0 assert isinstance(base.num('42.'), float) assert base.num(42.5) == 42.5 assert base.num('42.5') == 42.5 assert base.num_or_none('') is None assert base.num_or_none(None) is None assert base.num_or_none('1a') is None assert base.num_or_none('42') == 42 assert base.num_or_none('42.0') == 42.0
def read_color_palette_dict(color_palette: ColorPalette, d: Dict[str, str]): # { # "0": "#FFff0000", # "1": "#FF00ff00", # "254": "#66000000", # "255": "#00000000" # } color_palette.pal.clear() if "values" in d: d = d["values"] # nv = d.get('noDateValue') for key, color in d.items(): if key != 'nv': key = num(key) if str(color).startswith('#'): color = int(color[1:], 16) color_palette.pal[key] = color
def main_old(argv): srcwin = None skip = 1 srcfile = None dstfile = None band_nums = [] all_bands = False delim = ' ' skip_nodata = False src_nodata = [] dst_nodata = [] argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 0 # Parse command line arguments. i = 1 while i < len(argv): arg = str(argv[i]).lower() if arg.startswith('--'): arg = arg[1:] if arg == '-srcwin': srcwin = (int(argv[i + 1]), int(argv[i + 2]), int(argv[i + 3]), int(argv[i + 4])) i = i + 4 elif arg == '-skip': skip = int(argv[i + 1]) i = i + 1 elif arg in ['-b', '-band']: b = int(argv[i + 1]) i = i + 1 if b: band_nums.append(b) else: all_bands = True elif arg == '-allbands': all_bands = True elif arg == '-csv': delim = ',' elif arg in ['-skipnodata', '-skip_nodata']: skip_nodata = True elif arg in ['-nodatavalue', '-srcnodata']: src_nodata.append(num(argv[i + 1])) i = i + 1 elif arg == '-dstnodata': dst_nodata.append(num(argv[i + 1])) i = i + 1 elif srcfile is None: srcfile = arg elif dstfile is None: dstfile = arg elif arg == '-help': return Usage() else: return Usage() i = i + 1 if srcfile is None: return Usage() if all_bands: band_nums = None elif not band_nums: band_nums = 1 return gdal2xyz(srcfile=srcfile, dstfile=dstfile, srcwin=srcwin, skip=skip, band_nums=band_nums, delim=delim, skip_nodata=skip_nodata, src_nodata=src_nodata, dst_nodata=dst_nodata)
def main(argv): srcwin = None skip = 1 srcfile = None dstfile = None band_nums = [] all_bands = False delim = ' ' skip_no_data = False no_data_value = [] argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 0 # Parse command line arguments. i = 1 while i < len(argv): arg = argv[i] if arg == '-srcwin': srcwin = (int(argv[i + 1]), int(argv[i + 2]), int(argv[i + 3]), int(argv[i + 4])) i = i + 4 elif arg == '-skip': skip = int(argv[i + 1]) i = i + 1 elif arg == '-band': band_nums.append(int(argv[i + 1])) i = i + 1 elif arg == '--allBands': all_bands = True elif arg == '-csv': delim = ',' elif arg == '--skipNoData': skip_no_data = True elif arg == '-noDataValue': no_data_value.append(num(argv[i + 1])) i = i + 1 elif arg[0] == '-': return Usage() elif srcfile is None: srcfile = arg elif dstfile is None: dstfile = arg else: return Usage() i = i + 1 if srcfile is None: return Usage() if all_bands: band_nums = None elif not band_nums: band_nums = 1 return gdal2xyz(srcfile=srcfile, dstfile=dstfile, srcwin=srcwin, skip=skip, band_nums=band_nums, delim=delim, skip_no_data=skip_no_data, no_data_value=no_data_value)