Ejemplo n.º 1
0
def test(argv):
    in_dir = argv[1]
    dem_filename = argv[2]
    working_dir = argv[3]

    l_ListOfTOAImageFileNames = [
        os.path.join(in_dir, 'T36JTT_20160914T074612_B01.jp2'),
        os.path.join(in_dir, 'T36JTT_20160914T074612_B02.jp2'),
        os.path.join(in_dir, 'T36JTT_20160914T074612_B03.jp2'),
        os.path.join(in_dir, 'T36JTT_20160914T074612_B04.jp2'),
        os.path.join(in_dir, 'T36JTT_20160914T074612_B05.jp2'),
        os.path.join(in_dir, 'T36JTT_20160914T074612_B06.jp2'),
        os.path.join(in_dir, 'T36JTT_20160914T074612_B07.jp2'),
        os.path.join(in_dir, 'T36JTT_20160914T074612_B08.jp2'),
        os.path.join(in_dir, 'T36JTT_20160914T074612_B8A.jp2'),
        os.path.join(in_dir, 'T36JTT_20160914T074612_B09.jp2'),
        os.path.join(in_dir, 'T36JTT_20160914T074612_B10.jp2'),
        os.path.join(in_dir, 'T36JTT_20160914T074612_B11.jp2'),
        os.path.join(in_dir, 'T36JTT_20160914T074612_B12.jp2')
    ]

    maja_object = Sentinel2L1ImageFileReader()
    maja_object._toa_scalar_list = l_ListOfTOAImageFileNames
    maja_object._plugin = MajaSentinel2Plugin()

    dem = DEMBase()
    dem.initialize(dem_filename, working_dir, False)

    maja_object._dem = dem
    maja_object.generate_edg_images_from_toa(l_ListOfTOAImageFileNames,
                                             working_dir)
    otb_copy_image_to_file(maja_object._l2edgmasklist[0],
                           os.path.join(working_dir, "IPEDGMaskL2_R1.tif"))
    otb_copy_image_to_file(maja_object._l2edgmasklist[1],
                           os.path.join(working_dir, "IPEDGMaskL2_R2.tif"))
    otb_copy_image_to_file(maja_object._edgsubmask,
                           os.path.join(working_dir, "MaskOrMask12.tif"))
Ejemplo n.º 2
0
 def __init__(self):
     super(Sentinel2L1ImageFileReader, self).__init__()
     self._l2edg_pipeline = OtbPipelineManager()
     self._Satellite = "SENTINEL2"
     self._plugin = MajaSentinel2Plugin()
 def __init__(self):
     super(MajaSentinel2L2ImageReader, self).__init__()
     self.plugin = MajaSentinel2Plugin()
Ejemplo n.º 4
0
    def initialize(self, product_filename, validate=False, schema_path=None, tile_id=None):
        self.ProductFileName = product_filename
        self.PluginName = "SENTINEL2"
        LOGGER.info("Start Sentinel2 L1 ImageInformationProvider " + product_filename + "...")
        # detect correctly formatted
        if (("_MTD_SAFL1C_" not in product_filename and "MTD_MSIL1C" not in product_filename) or
                os.path.splitext(product_filename)[1] != ".xml"):
            return False

        try:
            headerHandler = MajaSentinel2L1MainXmlReader(product_filename, validate, schema_path,tile_id=tile_id)
        except Exception as e:
            LOGGER.info(e)
            return False
        self.HeaderHandler = headerHandler
        self.Satellite = headerHandler.satellite_name.upper()
        self.SatelliteID = self.Satellite.upper().replace("-","")
        self.UniqueSatellite = "SENTINEL-2_"
        self.LevelType = "L1VALD"
        self.FileCategory = "SSC"

        granule_id_split = headerHandler.granule_id.split("_")
        self.FileClass = granule_id_split[1]
        self.HeaderFilename = headerHandler.main_xml_file
        self.Prefix = granule_id_split[0]
        self.L1NoData = headerHandler.get_no_data()
        self.ReflectanceQuantification = 1.0 / headerHandler.quantification_value
        self.RealL1NoData = self.L1NoData * self.ReflectanceQuantification
        self.xmlTileFilename = headerHandler.XmlTileFileName
        LOGGER.info("Tile xml filename : " + self.xmlTileFilename)
        tile_handler = MajaSentinel2L1GranuleXmlReader(self.xmlTileFilename)
        self.TileHandler = tile_handler
        LOGGER.debug("TileId: " + self.HeaderHandler.TileId)
        self.Site = maja_utils.get_formated_site(self.HeaderHandler.TileId)
        self.TileHandler.TileId = self.Site

        self.ProductDate = date_utils.get_datetime_from_utc("UTC=" + tile_handler.sensing_time)
        self.ProductDateStr = self.ProductDate.strftime('%Y%m%d')
        LOGGER.debug("Product Date: " + self.ProductDateStr)
        self.ProductId = headerHandler.get_string_value_of("ProductURI")
        LOGGER.debug("ProductID: "+self.ProductId)

        self.GenerationDateStr = headerHandler.get_string_value_of("GenerationTime")
        self.AcquisitionStart = headerHandler.get_string_value_of("ProductStartTime")

        self.OrbitNumber = headerHandler.get_string_value_of("OrbitNumber")

        l_datastrip_split = tile_handler.datastrip_id.split("_")
        l_start_date_str = l_datastrip_split[-3]
        l_stop_date_str = l_datastrip_split[-2][1:]
        l_start_date_time = date_utils.get_datetime_from_yyyymmddthhmmss(l_start_date_str)
        l_stop_date_time = date_utils.get_datetime_from_yyyymmddthhmmss(l_stop_date_str)
        self.UTCValidityStart = date_utils.get_utc_from_datetime(l_start_date_time)
        LOGGER.debug("UTCValidityStart : " + self.UTCValidityStart)
        self.UTCValidityStop = date_utils.get_utc_from_datetime(l_stop_date_time)
        LOGGER.debug("UTCValidityStop : " + self.UTCValidityStop)

        self.ReferenceSiteDefinitionId = "UNKNOWN"

        # Not available in S2
        self.SOLHeaderFileName = ""
        self.SOLImageFileName = ""
        self.VIEHeaderFileName = ""
        self.VIEImageFileName = ""
        self.ListOfViewingAnglesPerBandAtL2Resolution = []
        self.ListOfViewingAnglesPerBandAtL2CoarseResolution = []
        self.ListOfViewingZenithAnglesPerBandAtL2CoarseResolution = []
        self.ListOfViewingAzimuthAnglesPerBandAtL2CoarseResolution = []
        l_MeanViewingZenithalAngles = []
        l_MeanViewingAzimuthalAngles = []
        for f in range(0, len(tile_handler.angles.viewing_incidence_angle.incidence_angles_mean)):
            angles = tile_handler.angles.viewing_incidence_angle.incidence_angles_mean[str(f)]
            self.ListOfViewingAnglesPerBandAtL2CoarseResolution.append(angles)
            self.ListOfViewingZenithAnglesPerBandAtL2CoarseResolution.append(angles["incidence_zenith_angle"])
            self.ListOfViewingAzimuthAnglesPerBandAtL2CoarseResolution.append(angles["incidence_azimuth_angle"])
            l_MeanViewingZenithalAngles.append(float(angles["incidence_zenith_angle"]))
            l_MeanViewingAzimuthalAngles.append(float(angles["incidence_azimuth_angle"]))
        self.ViewingAngle = {
            "incidence_zenith_angle": str(statistics.mean(l_MeanViewingZenithalAngles)),
            "incidence_azimuth_angle": str(statistics.mean(l_MeanViewingAzimuthalAngles))
            }
        l_bandsdefinition = MajaSentinel2Plugin().BandsDefinitions
        l_nbRes = len(l_bandsdefinition.ListOfL2Resolution)
        for r in range(0, l_nbRes):
            l_res = l_bandsdefinition.ListOfL2Resolution[r]
            l_l2bandcodes = l_bandsdefinition.get_list_of_l2_band_code(l_res)
            l_l2bandidx = [l_bandsdefinition.get_band_id_in_l2_coarse(b) for b in l_l2bandcodes]
            for b in l_l2bandidx:
                self.ListOfViewingAnglesPerBandAtL2Resolution.append(
                    self.ListOfViewingAnglesPerBandAtL2CoarseResolution[b])

        self.ViewingAngleGrids = []
        for grid in tile_handler.angles.viewing_incidence_angle.list_of_viewing_angles_grid:
            self.ViewingAngleGrids.append({
                "StepUnit":grid.step_unit,
                "ColStep":grid.col_step,
                "RowStep":grid.row_step,
                "Band":grid.band_id,
                "Detector":grid.detector_id,
                "Azimuth":grid.azimuth_values,
                "Zenith":grid.zenith_values
                })
        self.SolarAngle = tile_handler.angles.sun_angles.sun_angles_mean

        self.SolarAngleGrid["StepUnit"] = tile_handler.angles.sun_angles.step_unit
        self.SolarAngleGrid["ColStep"] = tile_handler.angles.sun_angles.col_step
        self.SolarAngleGrid["RowStep"] = tile_handler.angles.sun_angles.row_step
        self.SolarAngleGrid["Azimuth"] = tile_handler.angles.sun_angles.azimuth_angle_list_string_values
        self.SolarAngleGrid["Zenith"] = tile_handler.angles.sun_angles.zenith_angle_list_string_values

        # Area by resolution
        self.AreaByResolution = []
        for res in l_bandsdefinition.ListOfL2Resolution:
            res_m = l_bandsdefinition.get_l1_resolution(res)
            l_ul = tile_handler.get_geoposition_upperleftcorner(res_m)
            l_spa = tile_handler.get_geoposition_dims(res_m)
            l_size = tile_handler.get_size(res_m)
            curArea = Area()
            curArea.origin = (
                str(l_ul.x),
                str(l_ul.y))
            curArea.spacing = (
                str(l_spa.x),
                str(l_spa.y))
            curArea.size = (
                str(l_size.x),
                str(l_size.y))
            self.AreaByResolution.append(curArea)
        
        # Spectral information
        self.SpectralInfo = []
        l_pathGain = "//Product_Image_Characteristics/PHYSICAL_GAINS[@bandId='{}']"
        l_pathRadiance = "//Solar_Irradiance_List/SOLAR_IRRADIANCE[@bandId='{}']"
        l_pathWavelength = "//Spectral_Information_List/Spectral_Information[@bandId='{}']/Wavelength/{}"
        l_pathResponse = "//Spectral_Information_List/Spectral_Information[@bandId='{}']/Spectral_Response/{}"
        for b, bidx in l_bandsdefinition.L1BandMap.items():
            self.SpectralInfo.append({
                "Band":b,
                "PhysicalGain":float(headerHandler.get_string_value(l_pathGain.format(bidx))),
                "SolarIrradiance":headerHandler.get_string_value(l_pathRadiance.format(bidx)),
                "WavelengthMin":headerHandler.get_string_value(l_pathWavelength.format(bidx, "MIN")),
                "WavelengthMax":headerHandler.get_string_value(l_pathWavelength.format(bidx, "MAX")),
                "WavelengthCentral":headerHandler.get_string_value(l_pathWavelength.format(bidx, "CENTRAL")),
                "ResponseStep":headerHandler.get_string_value(l_pathResponse.format(bidx, "STEP")),
                "ResponseValues":headerHandler.get_string_value(l_pathResponse.format(bidx, "VALUES"))
                })

        # TODO CenterCorner
        l_resolution = 10
        l_boundingbox = tile_handler.get_geoposition_boundingbox(l_resolution)
        LOGGER.info("Geoposition BoundingBox computed: xmin, ymin, xmax, ymax: " + str(l_boundingbox.xmin) + ", "
                    + str(l_boundingbox.ymin) + ", " + str(l_boundingbox.xmax) + ", " + str(l_boundingbox.ymax) + ".")

        # Transform in Lat / Long coordinates
        # -------------------------------------------------------------------------
        # CSCode = EPSG:32615
        cs_code = tile_handler.reference_system_code
        cs_code = maja_utils.split_string(cs_code, ':')[-1]

        # Estimation of the coordinate of the central point
        l_inputpoint_0 = l_boundingbox.xmin + (l_boundingbox.xmax - l_boundingbox.xmin) / 2.0
        l_inputpoint_1 = l_boundingbox.ymin + (l_boundingbox.ymax - l_boundingbox.ymin) / 2.0
        LOGGER.debug(
            "Geoposition BoundingBox central point computed: x, y: " + str(l_inputpoint_0) + ", " + str(l_inputpoint_1))

        LOGGER.debug("Start Conversion ToWKT with the EPSG '" + cs_code + "'...")
        param_conv = {"carto.x": l_inputpoint_0,
                      "carto.y": l_inputpoint_1,
                      "mapproj": "epsg",
                      "mapproj.epsg.code": int(cs_code)
                      }
        conv_app = OtbAppHandler("ConvertCartoToGeoPoint", param_conv)
        LOGGER.debug("Start Conversion ToWKT done.")

        self.CenterCorner.longitude = conv_app.getoutput()["long"]
        self.CenterCorner.latitude = conv_app.getoutput()["lat"]
        self.CenterCorner.column = 0
        self.CenterCorner.line = 0
        conv_app = None

        return True
 def __init__(self):
     super(MajaSentinel2L2HeaderWriter, self).__init__()
     self.plugin = MajaSentinel2Plugin()