예제 #1
0
def main(argv):
    parser = GDALArgumentParser(description='Transforms files from ESRI prj format into WKT format')

    parser.add_argument("filenames", metavar='filename', type=str, nargs='*', help="esri .prj file")

    args = parser.parse_args(argv[1:])

    res = 1
    for filename in args.filenames:
        res = esri2wkt(filename)
    return res
예제 #2
0
def main(argv):
    parser = GDALArgumentParser()

    parser.add_argument("-authority",
                        dest="authority",
                        metavar='name',
                        type=str,
                        help="Authority name")

    group = parser.add_mutually_exclusive_group()
    group.add_argument("-wkt",
                       const='wkt',
                       dest="output_format",
                       action='store_const',
                       help='Well Known Text')
    group.add_argument("-pretty_wkt",
                       const='pretty_wkt',
                       dest="output_format",
                       action='store_const',
                       help='Pretty Well Known Text')
    group.add_argument("-proj4",
                       const='proj4',
                       dest="output_format",
                       action='store_const',
                       help='proj string')
    group.add_argument("-postgis",
                       const='postgis',
                       dest="output_format",
                       action='store_const',
                       help='postgis')
    group.add_argument("-xml",
                       const='xml',
                       dest="output_format",
                       action='store_const',
                       help='XML')
    group.add_argument("-copy",
                       const='copy',
                       dest="output_format",
                       action='store_const',
                       help='Table')

    args = parser.parse_args(argv[1:])

    if not args.output_format:
        args.output_format = 'pretty_wkt'
    return epsg_tr('-' + args.output_format, args.authority)
예제 #3
0
def main(argv):
    parser = GDALArgumentParser(formatter_class=RawDescriptionHelpFormatter,
                                description=textwrap.dedent('''\
            The gdal2xyz utility can be used to translate a raster file into xyz format.
            It can be used as an alternative to gdal_translate of=xyz,
            But supporting other options, for example:
            * Select more then one band;
            * Skip or replace nodata value;
            * Return the output as numpy arrays.'''))

    parser.add_argument("-skip",
                        dest="skip",
                        action="store_true",
                        default=1,
                        help="How many rows/cols to skip in each iteration.")

    parser.add_argument(
        "-srcwin",
        metavar=('xoff', 'yoff', 'xsize', 'ysize'),
        dest="srcwin",
        type=float,
        nargs=4,
        help=
        "Selects a subwindow from the source image for copying based on pixel/line location"
    )

    parser.add_argument(
        "-b",
        "-band",
        "--band",
        dest="band_nums",
        metavar="band",
        type=int,
        nargs='+',
        help="Select bands from the input spectral bands for output. "
        "Bands are numbered from 1 in the order spectral bands are specified. "
        "Multiple -b switches may be used. When no -b switch is used, the first band will be used."
        "In order to use all input bands set -allbands or -b 0..")

    parser.add_argument("-allbands",
                        "--allbands",
                        dest="allbands",
                        action="store_true",
                        help="Select all input bands.")

    parser.add_argument("-csv",
                        dest="delim",
                        const=',',
                        default=' ',
                        action="store_const",
                        help="Use comma instead of space as a delimiter.")

    parser.add_argument(
        "-skipnodata",
        "--skipnodata",
        "-skip_nodata",
        dest="skip_nodata",
        action="store_true",
        help=
        "Exclude the output lines with nodata value (as determined by srcnodata)."
    )

    parser.add_argument(
        "-srcnodata",
        '-nodatavalue',
        dest="src_nodata",
        type=Real,
        nargs='*',
        help="The nodata value of the dataset (for skipping or replacing) "
        "Default (None) - Use the dataset nodata value; "
        "Sequence/Number - Use the given nodata value (per band or per dataset)."
    )

    parser.add_argument(
        "-dstnodata",
        dest="dst_nodata",
        type=Real,
        nargs='*',
        help="Replace source nodata with a given nodata. "
        "Has an effect only if not setting -skipnodata. "
        "Default(None) - Use srcnodata, no replacement; "
        "Sequence/Number - Replace the srcnodata with the given nodata value "
        "(per band or per dataset).")

    parser.add_argument(
        "srcfile",
        metavar="src_dataset",
        type=str,
        help="The source dataset name. It can be either file name, "
        "URL of data source or subdataset name for multi-dataset files.")

    parser.add_argument("dstfile",
                        metavar="dst_dataset",
                        type=str,
                        help="The destination file name.")

    args = parser.parse_args(argv[1:])
    if args.allbands:
        args.band_nums = None
    elif not args.band_nums:
        args.band_nums = 1
    kwargs = vars(args)
    del kwargs["allbands"]
    try:
        return gdal2xyz(**kwargs)
    except IOError as e:
        print(e)
        return 1
예제 #4
0
def main(argv):
    parser = GDALArgumentParser()

    group = parser.add_mutually_exclusive_group()
    group.add_argument(
        "-xml",
        dest="xml",
        action="store_true",
        help=
        "The output report will be XML formatted for convenient post processing."
    )
    group.add_argument(
        "-lifonly",
        dest="lifonly",
        action="store_true",
        help=
        "The only output is filenames production from the LocationInfo request against "
        "the database (i.e. for identifying impacted file from VRT).")
    group.add_argument(
        "-valonly",
        dest="valonly",
        action="store_true",
        help=
        "The only output is the pixel values of the selected pixel on each of the selected bands."
    )
    parser.add_argument(
        "-plb",
        dest="plb",
        action="store_true",
        help=
        "The output will be a series of lines in the form of Pixel,Line,band0,band1... "
        "for each of the selected bands.")
    group.add_argument("-quiet",
                       dest="quiet",
                       action="store_true",
                       help="No output will be printed.")

    group = parser.add_mutually_exclusive_group()
    group.add_argument(
        "-l_srs",
        dest="srs",
        metavar='srs_def',
        type=str,
        help="The coordinate system of the input x, y location.")
    group.add_argument(
        "-geoloc",
        dest="geoloc",
        action="store_true",
        help=
        "Indicates input x,y points are in the georeferencing system of the image."
    )
    group.add_argument(
        "-llgeoloc",
        dest="llgeoloc",
        action="store_true",
        help="Indicates input x,y points are in the long, lat (geographic) "
        "based on the georeferencing system of the image.")
    group.add_argument("-wgs84",
                       dest="wgs84",
                       action="store_true",
                       help="Indicates input x,y points are WGS84 long, lat.")

    parser.add_argument(
        "-extent_strict",
        dest="allow_xy_outside_extent",
        action="store_false",
        help=
        "If set, input points outside the raster extent will raise an exception, "
        "otherwise a warning will be issued (unless quiet).")

    parser.add_argument(
        "-interp",
        dest="resample_alg",
        action="store_true",
        help=
        "If set, a Bilinear interpolation would be used, otherwise the NearestNeighbour sampling."
    )

    parser.add_argument(
        "-b",
        dest="band_nums",
        metavar="band",
        type=int,
        nargs='+',
        help=
        "Selects a band to query. Multiple bands can be listed. By default all bands are queried."
    )

    parser.add_argument(
        '-overview',
        dest="ovr_idx",
        metavar="overview_level",
        type=int,
        help=
        "Query the (overview_level)th overview (overview_level=1 is the 1st overview), "
        "instead of the base band. Note that the x,y location (if the coordinate system is "
        "pixel/line) must still be given with respect to the base band.")

    parser.add_argument(
        "-axis_order",
        dest="gis_order",
        choices=['gis', 'authority'],
        type=str,
        help=
        "X, Y Axis order: Traditional GIS, Authority complaint or otherwise utility default."
    )

    parser.add_argument("-oo",
                        dest="open_options",
                        metavar="NAME=VALUE",
                        help="Dataset open option (format specific).",
                        nargs='+')

    parser.add_argument("filename_or_ds",
                        metavar="filename",
                        type=str,
                        help="The source GDAL raster datasource name.")

    parser.add_argument(
        "xy",
        metavar="x y",
        nargs='*',
        type=float,
        help="series of X Y pairs of location of target pixel. "
        "By default the coordinate system "
        "is pixel/line unless -l_srs, -wgs84 or -geoloc supplied.")

    args = parser.parse_args(argv[1:])

    interactive_mode = len(args.xy) <= 1
    if not interactive_mode:
        args.x = np.array(args.xy[0::2])
        args.y = np.array(args.xy[1::2])

    if args.geoloc:
        args.srs = LocationInfoSRS.SameAsDS_SRS
    elif args.llgeoloc:
        args.srs = LocationInfoSRS.SameAsDS_SRS_GeogCS
    elif args.wgs84:
        args.srs = 4326

    args.gis_order = \
        args.srs and (args.srs != LocationInfoSRS.SameAsDS_SRS) if args.gis_order is None \
        else str(args.gis_order).lower() == 'gis'

    if args.xml:
        args.output_mode = LocationInfoOutput.XML
    elif args.lifonly:
        args.output_mode = LocationInfoOutput.LifOnly
    elif args.valonly:
        args.output_mode = LocationInfoOutput.ValOnly
    elif args.plb:
        args.output_mode = LocationInfoOutput.PixelLineVal
    elif args.quiet:
        args.output_mode = LocationInfoOutput.Quiet
    else:
        args.output_mode = LocationInfoOutput.PixelLineValVerbose

    args.resample_alg = gdal.GRIORA_Bilinear if args.resample_alg else gdal.GRIORA_NearestNeighbour

    kwargs = vars(args)
    del kwargs["xy"]

    del kwargs["geoloc"]
    del kwargs["llgeoloc"]
    del kwargs["wgs84"]

    del kwargs["xml"]
    del kwargs["lifonly"]
    del kwargs["valonly"]
    del kwargs["plb"]
    del kwargs["quiet"]

    try:
        if interactive_mode:
            is_pixel_line = args.srs == LocationInfoSRS.PixelLine
            while True:
                xy = input(f"Enter {'pixel line' if is_pixel_line else 'X Y'} "
                           f"values separated by space, and press Return.\n")
                xy = xy.strip().split(' ', 1)
                kwargs['x'], kwargs['y'] = float(xy[0]), float(xy[1])
                gdallocationinfo_util(**kwargs)
        else:
            gdallocationinfo_util(**kwargs)
            return 0
    except IOError as e:
        print(e)
        return 1
예제 #5
0
def main(argv):
    parser = GDALArgumentParser(
        # add an explicit --help option because the standard -h/--help option is not valid as -h is an alpha option
        add_help='--help',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description=textwrap.dedent('''\
                    Command line raster calculator with numpy syntax.
                    Use any basic arithmetic supported by numpy arrays such as +, -, *, and
                    along with logical operators such as >.
                    Note that all files must have the same dimensions (unless extent option is used),
                    but no projection checking is performed (unless projectionCheck option is used).'''))

    parser.add_argument("--calc", dest="calc", type=str, required=True, nargs='*', action="extend",
                        help="calculation in numpy syntax using +-/* or any numpy array functions (i.e. log10()). "
                             "May appear multiple times to produce a multi-band file", metavar="expression")
    add_alpha_args(parser, argv)

    parser.add_argument("--outfile", dest="outF", required=True, metavar="filename",
                        help="output file to generate or fill")
    parser.add_argument("--NoDataValue", dest="NoDataValue", type=float, metavar="value",
                        help="output nodata value (default datatype specific value)")
    parser.add_argument("--hideNoData", dest="hideNoData", action="store_true",
                        help="ignores the NoDataValues of the input rasters")
    parser.add_argument("--type", dest="type", type=str, metavar="datatype", choices=GDALDataTypeNames,
                        help="output datatype")
    parser.add_argument("--format", dest="format", type=str, metavar="gdal_format",
                        help="GDAL format for output file")
    parser.add_argument(
        "--creation-option", "--co", dest="creation_options", default=[], action="append", metavar="option",
        help="Passes a creation option to the output format driver. Multiple "
             "options may be listed. See format specific documentation for legal "
             "creation options for each format.")
    parser.add_argument("--allBands", dest="allBands", type=str, default="", metavar="[a-z, A-Z]",
                        help="process all bands of given raster [a-z, A-Z]")
    parser.add_argument("--overwrite", dest="overwrite", action="store_true",
                        help="overwrite output file if it already exists")
    parser.add_argument("--debug", dest="debug", action="store_true", help="print debugging information")
    parser.add_argument("--quiet", dest="quiet", action="store_true", help="suppress progress messages")

    parser.add_argument("--color-table", type=str, dest="color_table", help="color table file name")

    group = parser.add_mutually_exclusive_group()
    group.add_argument("--extent", dest="extent",
                       choices=[e.name.lower() for e in Extent],
                       help="how to treat mixed geotrasnforms")
    group.add_argument("--projwin", dest="projwin", type=float, nargs=4, metavar=('ulx', 'uly', 'lrx', 'lry'),
                       help="extent corners given in georeferenced coordinates")

    parser.add_argument("--projectionCheck", dest="projectionCheck", action="store_true",
                        help="check that all rasters share the same projection")

    opts = parser.parse_args(argv[1:], optfile_arg="--optfile")

    try:
        # create the input_files dict from the alpha arguments ('-a' and '--a_band')
        input_files = {}
        for alpha in AlphaList:
            alpha_val = getattr(opts, alpha, None)
            if alpha_val is not None:
                delattr(opts, alpha)
                alpha_val = [s.strip('"') for s in alpha_val]
                input_files[alpha] = alpha_val if len(alpha_val) > 1 else alpha_val[0]
                band_key = alpha + '_band'
                band_val = getattr(opts, band_key, None)
                if band_val is not None:
                    delattr(opts, band_key)
                    input_files[band_key] = band_val if len(band_val) > 1 else band_val[0]
        opts.input_files = input_files
        opts.calc = [s.strip('"') for s in opts.calc]
        if not hasattr(opts, "user_namespace"):
            opts.user_namespace = {}
        # opts.calc = str(opts.calc).strip()
        doit(opts)
    except Exception as e:
        print(e)
        return 1