layer2img.py (1823B) - Raw
1 #!/usr/bin/python3 2 import argparse 3 import geopandas 4 import psycopg2 5 import matplotlib.pyplot as plt 6 7 INCH = 25.4 # mm 8 BROWN = '#d15c00' # CMYK: 0_56_100_18 9 10 11 def plt_size(string): 12 if not string: 13 return None 14 try: 15 w, h = string.split("x") 16 return float(w) / INCH, float(h) / INCH 17 except Exception as e: 18 raise argparse.ArgumentTypeError from e 19 20 21 def parse_args(): 22 parser = argparse.ArgumentParser( 23 description='Convert geopackage to an image') 24 group1 = parser.add_mutually_exclusive_group() 25 group1.add_argument('--infile') 26 group1.add_argument('--table') 27 parser.add_argument('-o', '--outfile', metavar='<file>') 28 parser.add_argument( 29 '--dpi', type=int, help='Dots per inch', default=300) 30 parser.add_argument( 31 '--size', type=plt_size, help='Figure size in mm (WWxHH)') 32 33 return parser.parse_args() 34 35 36 def read_layer(maybe_table, maybe_file): 37 if maybe_table: 38 conn = psycopg2.connect("host=127.0.0.1 dbname=osm user=osm") 39 sql = "SELECT geom FROM %s" % maybe_table 40 return geopandas.read_postgis(sql, con=conn, geom_col='geom') 41 elif maybe_file: 42 return geopandas.read_file(maybe_file) 43 44 45 def plot_layer(layer, ax, color): 46 layer.plot(ax=ax, color=BROWN, linewidth=.5) 47 48 49 def main(): 50 args = parse_args() 51 layer = read_layer(args.table, args.infile) 52 53 fig, ax = plt.subplots() 54 if args.size: 55 fig.set_size_inches(args.size) 56 57 plot_layer(layer, ax=ax, color=BROWN) 58 59 ax.axis('off') 60 ax.margins(0, 0) 61 fig.tight_layout(0) 62 if args.outfile: 63 fig.savefig( 64 args.outfile, bbox_inches=0, dpi=args.dpi, 65 pil_kwargs={'compression': 'tiff_deflate'}, 66 ) 67 else: 68 plt.show() 69 70 71 if __name__ == '__main__': 72 main()