Beispiel #1
0
def get_image_bounds(image_file: str) -> str:
    """Loads the boundaries from an image file
    Arguments:
        image_file: path to the image to load the bounds from
    Return:
        Returns the GEOJSON of the bounds if they could be loaded and converted (if necessary).
        None is returned if the bounds are loaded or can't be converted
    """
    # If the file has a geo shape we store it for clipping
    bounds = image_get_geobounds(image_file)
    epsg = get_epsg(image_file)
    if bounds[0] != np.nan:
        ring = ogr.Geometry(ogr.wkbLinearRing)
        ring.AddPoint(bounds[2], bounds[1])     # Upper left
        ring.AddPoint(bounds[3], bounds[1])     # Upper right
        ring.AddPoint(bounds[3], bounds[0])     # lower right
        ring.AddPoint(bounds[2], bounds[0])     # lower left
        ring.AddPoint(bounds[2], bounds[1])     # Closing the polygon

        poly = ogr.Geometry(ogr.wkbPolygon)
        poly.AddGeometry(ring)

        ref_sys = osr.SpatialReference()
        if ref_sys.ImportFromEPSG(int(epsg)) == ogr.OGRERR_NONE:
            poly.AssignSpatialReference(ref_sys)
            return geometry_to_geojson(poly)

        logging.warning("Failed to import EPSG %s for image file %s", str(epsg), image_file)

    return None
    def find_image_files(self, files):
        """Finds files that are needed for extracting plots from an orthomosaic

        Args:
            files(list): the list of file to look through and access

        Returns:
            Returns a dict of georeferenced image files (indexed by filename and containing an
            object with the calculated image bounds as an ogr polygon and a list of the
            bounds as a tuple)

            The bounds are assumed to be rectilinear with the upper-left corner directly
            pulled from the file and the lower-right corner calculated based upon the geometry
            information stored in the file.

            The polygon points start at the upper left corner and proceed clockwise around the
            boundary. The returned polygon is closed: the first and last point are the same.

            The bounds tuple contains the min and max Y point values, followed by the min and
            max X point values.
        """
        imagefiles = {}

        for onefile in files:
            ext = os.path.splitext(os.path.basename(onefile))[1].lstrip('.')
            if not ext in self.known_non_image_ext:
                if file_is_image_type(self.args.identify_binary, onefile,
                                      onefile +
                                      self.file_infodata_file_ending):
                    # If the file has a geo shape we store it for clipping
                    bounds = image_get_geobounds(onefile)
                    epsg = get_epsg(onefile)
                    if bounds[0] != np.nan:
                        ring = ogr.Geometry(ogr.wkbLinearRing)
                        ring.AddPoint(bounds[2], bounds[1])  # Upper left
                        ring.AddPoint(bounds[3], bounds[1])  # Upper right
                        ring.AddPoint(bounds[3], bounds[0])  # lower right
                        ring.AddPoint(bounds[2], bounds[0])  # lower left
                        ring.AddPoint(bounds[2],
                                      bounds[1])  # Closing the polygon

                        poly = ogr.Geometry(ogr.wkbPolygon)
                        poly.AddGeometry(ring)

                        ref_sys = osr.SpatialReference()
                        if ref_sys.ImportFromEPSG(
                                int(epsg)) != ogr.OGRERR_NONE:
                            logging.error(
                                "Failed to import EPSG %s for image file %s",
                                str(epsg), onefile)
                        else:
                            poly.AssignSpatialReference(ref_sys)

                        imagefiles[onefile] = {'bounds': poly}

        # Return what we've found
        return imagefiles
Beispiel #3
0
def load_image_files(files):
    """Loads image file nboundaries
    Args:
        files(list): the list of file to look through and access
    Returns:
        Returns a dict of georeferenced image files (indexed by filename and containing an
        object with the calculated image bounds as an ogr polygon and a list of the
        bounds as a tuple)

        The bounds are assumed to be rectilinear with the upper-left corner directly
        pulled from the file and the lower-right corner calculated based upon the geometry
        information stored in the file.

        The polygon points start at the upper left corner and proceed clockwise around the
        boundary. The returned polygon is closed: the first and last point are the same.

        The bounds tuple contains the min and max Y point values, followed by the min and
        max X point values.
    """
    imagefiles = {}

    for onefile in files:
        # If the file has a geo shape we store it for clipping
        bounds = image_get_geobounds(onefile)
        epsg = get_epsg(onefile)
        if bounds[0] != np.nan:
            ring = ogr.Geometry(ogr.wkbLinearRing)
            ring.AddPoint(bounds[2], bounds[1])  # Upper left
            ring.AddPoint(bounds[3], bounds[1])  # Upper right
            ring.AddPoint(bounds[3], bounds[0])  # lower right
            ring.AddPoint(bounds[2], bounds[0])  # lower left
            ring.AddPoint(bounds[2], bounds[1])  # Closing the polygon

            poly = ogr.Geometry(ogr.wkbPolygon)
            poly.AddGeometry(ring)

            ref_sys = osr.SpatialReference()
            if epsg:
                if ref_sys.ImportFromEPSG(int(epsg)) != ogr.OGRERR_NONE:
                    raise RuntimeError("Failed to import EPSG " + str(epsg) +
                                       " for image file " + onefile)
                else:
                    poly.AssignSpatialReference(ref_sys)
            else:
                raise RuntimeError("File is missing an EPSG code: " + onefile)

            imagefiles[onefile] = {'bounds': poly}

    # Return what we've found
    return imagefiles
    def get_image_bounds_json(file_path: str,
                              default_epsg: int = None) -> Optional[str]:
        """Loads the boundaries of the image file and returns the GeoJSON
           representing the bounds (including EPSG code)
        Arguments:
            file_path: path to the file from which to load the bounds
            default_epsg: the default EPSG to assume if a file has a boundary but not a coordinate system
        Return:
            Returns the JSON representing the image boundary, or None if the
            bounds could not be loaded
        Notes:
            If a file doesn't have a coordinate system and a default epsg is specified, the
            return JSON will use the default_epsg.
            If a file doesn't have a coordinate system and there isn't a default epsg specified, the boundary
            of the image is not returned (None) and a warning is logged.
        """
        # Get the bounds (if they exist)
        bounds = image_get_geobounds(file_path)
        if bounds[0] == np.nan:
            return None

        epsg = get_epsg(file_path)
        if epsg is None:
            if default_epsg:
                epsg = default_epsg
            else:
                logging.warning(
                    "Files does not have a coordinate system defined and no default was specified: '%s'",
                    file_path)
                return None

        ring = ogr.Geometry(ogr.wkbLinearRing)
        ring.AddPoint(bounds[2], bounds[1])  # Upper left
        ring.AddPoint(bounds[3], bounds[1])  # Upper right
        ring.AddPoint(bounds[3], bounds[0])  # lower right
        ring.AddPoint(bounds[2], bounds[0])  # lower left
        ring.AddPoint(bounds[2], bounds[1])  # Closing the polygon

        poly = ogr.Geometry(ogr.wkbPolygon)
        poly.AddGeometry(ring)

        ref_sys = osr.SpatialReference()
        if ref_sys.ImportFromEPSG(int(epsg)) == ogr.OGRERR_NONE:
            poly.AssignSpatialReference(ref_sys)
            return geometry_to_geojson(poly)

        logging.error("Failed to import EPSG %s for image file %s", str(epsg),
                      file_path)
        return None
Beispiel #5
0
    def get_maskfilename_bounds(self, file_name, datestamp):
        """Determines the name of the masking file and loads the boundaries of the file
        Args:
            file_name(str): path of the file to create a mask from
            datestamp(str): the date to use when creating file paths
        Return:
        """
        mask_name, bounds = (None, None)

        if not self.get_terraref_metadata is None:
            key = 'left' if file_name.endswith('_left.tif') else 'right'
            mask_name = self.sensors.create_sensor_path(datestamp, opts=[key])
            bounds = geojson_to_tuples(self.get_terraref_metadata['spatial_metadata'][key]['bounding_box'])
        else:
            mask_name = self.sensors.create_sensor_path(datestamp)
            bounds = image_get_geobounds(file_name)
            bounds_len = len(bounds)
            if bounds_len <= 0 or bounds[0] == np.nan:
                bounds = None

        return (mask_name, bounds)
    def find_shape_image_files(self, files, triggering_file):
        """Finds files that are needed for extracting plots from an orthomosaic

        Args:
            files(list): the list of file to look through and access
            triggering_file(str): optional parameter specifying the file that triggered the
            extraction

        Returns:
            Returns a list containing the shapefile name, its optional associated DBF file,
            and a dict of georeferenced image files (indexed by filename and containing an
            object with the calculated image bounds as an ogr polygon and a list of the
            bounds as a tuple)

            The bounds are assumed to be rectilinear with the upper-left corner directly
            pulled from the file and the lower-right corner calculated based upon the geometry
            information stored in the file.

            The polygon points start at the upper left corner and proceed clockwise around the
            boundary. The returned polygon is closed: the first and last point are the same.

            The bounds tuple contains the min and max Y point values, followed by the min and
            max X point values.
        """
        shapefile, shxfile, dbffile = None, None, None
        imagefiles = {}

        for onefile in files:
            if onefile.endswith(".shp") and shapefile is None:
                # We give priority to the shapefile that triggered the extraction over any other
                # shapefiles that may exist
                if triggering_file is None or triggering_file.endswith(
                        onefile):
                    shapefile = onefile

                    filename_test = os.path.splitext(shapefile)[0] + ".shx"
                    if os.path.isfile(filename_test):
                        shxfile = filename_test

                    filename_test = os.path.splitext(shapefile)[0] + ".dbf"
                    if os.path.isfile(filename_test):
                        dbffile = filename_test
            else:
                ext = os.path.splitext(
                    os.path.basename(onefile))[1].lstrip('.')
                if not ext in self.known_non_image_ext:
                    if file_is_image_type(
                            self.args.identify_binary, onefile,
                            onefile + self.file_infodata_file_ending):
                        # If the file has a geo shape we store it for clipping
                        bounds = image_get_geobounds(onefile)
                        epsg = get_epsg(onefile)
                        if bounds[0] != nan:
                            ring = ogr.Geometry(ogr.wkbLinearRing)
                            ring.AddPoint(bounds[2], bounds[1])  # Upper left
                            ring.AddPoint(bounds[3], bounds[1])  # Upper right
                            ring.AddPoint(bounds[3], bounds[0])  # lower right
                            ring.AddPoint(bounds[2], bounds[0])  # lower left
                            ring.AddPoint(bounds[2],
                                          bounds[1])  # Closing the polygon

                            poly = ogr.Geometry(ogr.wkbPolygon)
                            poly.AddGeometry(ring)

                            ref_sys = osr.SpatialReference()
                            if ref_sys.ImportFromEPSG(
                                    int(epsg)) != ogr.OGRERR_NONE:
                                logging.error(
                                    "Failed to import EPSG %s for image file %s",
                                    str(epsg), onefile)
                            else:
                                poly.AssignSpatialReference(ref_sys)

                            # pylint: disable=line-too-long
                            imagefiles[onefile] = {'bounds': poly}
                            # pylint: enable=line-too-long

        # Return what we've found
        return (shapefile, shxfile, dbffile, imagefiles)