Ejemplo n.º 1
0
    def _build_requests(self, bbox, size_x, size_y, timestamp, time_interval):
        """ Build requests
        """
        evalscript = """
            //VERSION=3

            function setup() {
                return {
                    input: ["DEM"],
                    output:{
                        id: "default",
                        bands: 1,
                        sampleType: SampleType.UINT16
                    }
                }
            }

            function evaluatePixel(sample) {
                return [sample.DEM]
            }
        """

        request = SentinelHubRequest(
            evalscript=evalscript,
            input_data=[
                SentinelHubRequest.input_data(data_source=self.data_source)
            ],
            responses=[
                SentinelHubRequest.output_response('default', MimeType.TIFF)
            ],
            bbox=bbox,
            size=(size_x, size_y),
            data_folder=self.cache_folder)

        return [request]
Ejemplo n.º 2
0
def get_true_color_request(time_interval, betsiboka_bbox, betsiboka_size,
                           config):

    evalscript_true_color = """
        //VERSION=3
        function setup() {
            return {
                input: [{
                    bands: ["B02", "B03", "B04"] // B, G, R
                }],
                output: { bands: 3 }
            };
        }
        function evaluatePixel(sample) {
            return [sample.B04, sample.B03, sample.B02];
        }
    """

    return SentinelHubRequest(
        evalscript=evalscript_true_color,
        input_data=[
            SentinelHubRequest.input_data(
                data_collection=DataCollection.SENTINEL2_L1C,
                time_interval=time_interval,
                mosaicking_order='leastCC')
        ],
        responses=[
            SentinelHubRequest.output_response('default', MimeType.PNG)
        ],
        bbox=betsiboka_bbox,
        size=betsiboka_size,
        config=config)
Ejemplo n.º 3
0
def get_image_data(datum, bounding_box, config):
    evalscript_true_color = """
    //VERSION=3

    function setup() {
        return {
            input: [{
                bands: ["B02", "B03", "B04"]
            }],
            output: {
                bands: 3
            }
        };
    }

    function evaluatePixel(sample) {
        return [3.5*sample.B04, 3.5*sample.B03, 3.5*sample.B02];
    }
    """

    request = SentinelHubRequest(
        evalscript=evalscript_true_color,
        input_data=[
            SentinelHubRequest.input_data(
                data_collection=DataCollection.SENTINEL2_L1C,
                time_interval=datum)
        ],
        responses=[
            SentinelHubRequest.output_response('default', MimeType.PNG)
        ],
        bbox=bounding_box,
        size=(1000, 1000),
        config=config)

    return request.get_data()[0]
Ejemplo n.º 4
0
    def _prepare_api_requests(self):
        """ Prepare a list of Process API requests defining what data will be downloaded
        """
        timestamps = self.get_timestamps()
        evalscript = get_s2_evalscript(all_bands=self.cloud_detector.all_bands, reflectance=False)

        api_requests = []
        for timestamp in timestamps:
            request = SentinelHubRequest(
                evalscript=evalscript,
                input_data=[
                    SentinelHubRequest.input_data(
                        data_collection=DataCollection.SENTINEL2_L1C,
                        time_interval=(timestamp - self.time_difference, timestamp + self.time_difference),
                        **self.kwargs
                    )
                ],
                responses=[
                    SentinelHubRequest.output_response('default', MimeType.TIFF),
                    SentinelHubRequest.output_response('userdata', MimeType.JSON)
                ],
                bbox=self.bbox,
                size=self.size,
                resolution=self.resolution,
                config=self.config,
                data_folder=self.data_folder
            )
            api_requests.append(request)

        return api_requests
Ejemplo n.º 5
0
    def _create_sh_request(self, date_from, date_to, bbox, size_x, size_y):
        """ Create an instance of SentinelHubRequest
        """
        responses = [
            SentinelHubRequest.output_response(btype.id, MimeType.TIFF)
            for btype in self.requested_bands
        ]
        responses.append(
            SentinelHubRequest.output_response('userdata', MimeType.JSON))

        return SentinelHubRequest(
            evalscript=self.generate_evalscript(),
            input_data=[
                SentinelHubRequest.input_data(
                    data_source=self.data_source,
                    time_interval=(date_from, date_to),
                    mosaicking_order=self.mosaicking_order,
                    maxcc=self.maxcc,
                    other_args=self.aux_request_args)
            ],
            responses=responses,
            bbox=bbox,
            size=(size_x, size_y),
            data_folder=self.cache_folder,
            config=self.config)
def getSatelliteImage(box, size,folder,date_range,mosaick,config):
    
    """
    This function sends a request to SentinelHub through the API to get an image of a certain bounding.
    
    Parameters
    ----------
    box : box returne from checkSize.
    size : size returned from checkSize.
    folder : folder location to store image.
    date_range : list with a start and end date for image search.
    mosaick : what to filter the images based off.
    config : configuration set up with API.

    Returns
    -------
    Image which is a list with RGB values for each pixel.

    """
    
    evalscript_true_color = """
    //VERSION=3

    function setup() {
        return {
            input: [{
                bands: ["B02", "B03", "B04"]
            }],
            output: {
                bands: 3
            }
        };
    }

    function evaluatePixel(sample) {
        return [sample.B04, sample.B03, sample.B02];
    }
    """
    
    request_true_color = SentinelHubRequest(
    data_folder=folder,
    evalscript=evalscript_true_color,
    input_data=[
        SentinelHubRequest.input_data(
            data_collection=DataCollection.SENTINEL2_L1C,
            time_interval=(date_range[0], date_range[1]),
            mosaicking_order=mosaick
        )
    ],
    responses=[
        SentinelHubRequest.output_response('default', MimeType.PNG)
    ],
    bbox=box,
    size=size,
    config=config
    )
    
    image = request_true_color.get_data(save_data=True)
    
    return image
Ejemplo n.º 7
0
 def request(self, config, dir_save):
     input_data = [SentinelHubRequest.input_data(data_collection=self.dataset, time_interval=self.time_period)]
     response = [SentinelHubRequest.output_response("default", MimeType.TIFF)]
     kwargs = {"evalscript": self.eval_script, "input_data": input_data, "responses": response, "bbox": self.bbox,
               "size": self.bbox_size, "config": config}
     if dir_save is not None:
         kwargs["data_folder"] = dir_save
     return SentinelHubRequest(**kwargs)
Ejemplo n.º 8
0
    def test_preview_mode(self):
        """ Test downloading three bands of L1C
        """
        evalscript = """
            //VERSION=3

            function setup() {
                return {
                    input: [{
                        bands: ["B02", "B03", "B04"],
                        units: "DN"
                    }],
                    output: {
                        bands: 3,
                        sampleType: "UINT16"
                    }
                };
            }

            function evaluatePixel(sample) {
                return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02];
            }
        """

        request = SentinelHubRequest(
            evalscript=evalscript,
            input_data=[
                SentinelHubRequest.input_data(
                    data_collection=DataCollection.SENTINEL2_L1C,
                    time_interval=('2017-10-14T00:12:03',
                                   '2017-12-15T23:12:04'),
                    mosaicking_order='leastCC',
                    other_args={'dataFilter': {
                        'previewMode': 'PREVIEW'
                    }})
            ],
            responses=[
                SentinelHubRequest.output_response('default', MimeType.TIFF)
            ],
            bbox=BBox(bbox=[
                1155360.393335921, 5285081.168940068, 1156965.063795706,
                5286609.808304847
            ],
                      crs=CRS.POP_WEB),
            resolution=(260.0, 260.0))

        img = request.get_data(max_threads=3)[0]

        self.assertEqual(img.shape, (6, 6, 3))
        self.test_numpy_data(img,
                             exp_min=330,
                             exp_max=3128,
                             exp_mean=1787.5185)
def sentinel_request(coords, date_range):
    resolution = 30
    fire_bbox = BBox(bbox=coords, crs=CRS.WGS84)
    fire_box_size = bbox_to_dimensions(fire_bbox, resolution=resolution)

    print(f'Image shape at {resolution} m resolution: {fire_box_size} pixels')

    evalscript_true_color = """
        //VERSION=3

        function setup() {
            return {
                input: [{
                    bands: ["B02", "B03", "B04"]
                }],
                output: {
                    bands: 3
                }
            };
        }

        function evaluatePixel(sample) {
            return [sample.B04, sample.B03, sample.B02];
        }
    """

    request_true_color = SentinelHubRequest(
        evalscript=evalscript_true_color,
        input_data=[
            SentinelHubRequest.input_data(data_source=DataSource.LANDSAT8_L1C,
                                          time_interval=date_range,
                                          mosaicking_order='leastCC')
        ],
        responses=[
            SentinelHubRequest.output_response('default', MimeType.PNG)
        ],
        bbox=fire_bbox,
        size=fire_box_size,
        config=config)

    true_color_imgs = request_true_color.get_data()

    print(
        f'Returned data is of type = {type(true_color_imgs)} and length {len(true_color_imgs)}.'
    )
    print(
        f'Single element in the list is of type {type(true_color_imgs[-1])} and has shape {true_color_imgs[-1].shape}'
    )

    image = true_color_imgs[0]
    print(f'Image type: {image.dtype}')
    return image
Ejemplo n.º 10
0
    def test_bbox_geometry(self):
        """ Test intersection between bbox and geometry
        """
        evalscript = """
            //VERSION=3

            function setup() {
                return {
                    input: [{
                        bands: ["B02", "B03", "B04"],
                        units: "REFLECTANCE"
                    }],
                    output: {
                        bands: 3
                    }
                };
            }

            function evaluatePixel(sample) {
                return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02];
            }
        """

        delta = 0.2
        bbox = BBox(bbox=[46.16, -16.15, 46.51, -15.58], crs=CRS.WGS84)
        geometry = Geometry(bbox.geometry, crs=bbox.crs)
        bbox_translated = BBox(bbox=[
            46.16 + delta, -16.15 + delta, 46.51 + delta, -15.58 + delta
        ],
                               crs=CRS.WGS84)

        request = SentinelHubRequest(
            evalscript=evalscript,
            input_data=[
                SentinelHubRequest.input_data(
                    data_collection=DataCollection.SENTINEL2_L1C,
                    time_interval=('2017-12-15T07:12:03',
                                   '2017-12-15T07:12:04'),
                    maxcc=0.8)
            ],
            responses=[
                SentinelHubRequest.output_response('default', MimeType.JPG)
            ],
            geometry=geometry,
            bbox=bbox_translated,
            size=(512, 856))

        img = request.get_data(max_threads=3)[0]

        self.assertEqual(img.shape, (856, 512, 3))
        self.test_numpy_data(img, exp_min=0, exp_max=255, exp_mean=22.625)
Ejemplo n.º 11
0
    def test_resolution_parameter(self):
        """ Test downloading three bands of L1C
        """
        evalscript = """
            //VERSION=3

            function setup() {
                return {
                    input: [{
                        bands: ["B02", "B03", "B04"],
                        units: "DN"
                    }],
                    output: {
                        bands: 3,
                        sampleType: "UINT16"
                    }
                };
            }

            function evaluatePixel(sample) {
                return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02];
            }
        """

        request = SentinelHubRequest(
            evalscript=evalscript,
            input_data=[
                SentinelHubRequest.input_data(
                    data_source=DataSource.SENTINEL2_L1C,
                    time_interval=('2017-10-14T00:12:03',
                                   '2017-12-15T23:12:04'),
                    mosaicking_order='leastCC')
            ],
            responses=[
                SentinelHubRequest.output_response('default', MimeType.TIFF)
            ],
            bbox=BBox(bbox=[
                1155360.393335921, 5285081.168940068, 1156965.063795706,
                5286609.808304847
            ],
                      crs=CRS.POP_WEB),
            resolution=(10.0, 10.0))

        img = request.get_data(max_threads=3)[0]

        self.assertEqual(img.shape, (153, 160, 3))
        self.test_numpy_data(img,
                             exp_min=670,
                             exp_max=6105,
                             exp_mean=1848.2646)
def getPSRI(box, size, folder, date_range, mosaick, config):
    evalscript_true_color = """
    //VERSION=3

    let minVal = -0.2;
    let maxVal = 0.4;

    let viz = new HighlightCompressVisualizerSingle(minVal, maxVal);

    function evaluatePixel(samples) {
        let val = (samples.B06 > 0) ? (samples.B04 - samples.B02) / samples.B06 : JAVA_DOUBLE_MAX_VAL;
        return viz.process(val);
    }

    function setup() {
      return {
        input: [{
          bands: [
              "B02",
              "B04",
              "B06"
          ]
        }],
        output: { bands: 1 }
      }
    }
    """
    
    request_true_color = SentinelHubRequest(
    data_folder=folder,
    evalscript=evalscript_true_color,
    input_data=[
        SentinelHubRequest.input_data(
            data_collection=DataCollection.SENTINEL2_L1C,
            time_interval=(date_range[0], date_range[1]),
            mosaicking_order=mosaick
        )
    ],
    responses=[
        SentinelHubRequest.output_response('default', MimeType.PNG)
    ],
    bbox=box,
    size=size,
    config=config
    )
    
    image = request_true_color.get_data(save_data=True)
    
    return image
Ejemplo n.º 13
0
    def test_conflicting_service_url_restrictions(self):
        request_params = dict(
            evalscript='',
            input_data=[
                SentinelHubRequest.input_data(
                    data_collection=DataCollection.LANDSAT8),
                SentinelHubRequest.input_data(
                    data_collection=DataCollection.SENTINEL3_OLCI)
            ],
            responses=[SentinelHubRequest.output_response('default', 'tiff')],
            bbox=BBox(bbox=[46.16, -16.15, 46.51, -15.58], crs=CRS.WGS84),
            size=(512, 856),
            config=self.CONFIG)

        with self.assertRaises(ValueError):
            SentinelHubRequest(**request_params)
Ejemplo n.º 14
0
    def request(self, scene, bbox, shape):
        x, y = shape
        evalscript = '''//VERSION=3
                    function setup() {
                      return {
                        input: ["POLAR"],
                        output: { id:"default", bands: 1, sampleType: SampleType.FLOAT32}
                      }
                    }
            
                    function evaluatePixel(samples) {
                      return [samples.POLAR]
                    }'''.replace('POLAR', scene.polar)

        request = SentinelHubRequest(
            evalscript=evalscript,
            input_data=[{
                "type": "S1GRD",
                "dataFilter": {
                    "timeRange": {
                        "from": scene.from_time.strftime('%Y-%m-%dT%H:%M:%SZ'),
                        "to": scene.to_time.strftime('%Y-%m-%dT%H:%M:%SZ')
                    },
                    "acquisitionMode": "IW",
                    "polarization": "DV",
                    "orbitDirection ": scene.orbit_path
                },
                "processing": {
                    "backCoeff": "GAMMA0_ELLIPSOID",
                    "orthorectify": "true"
                }
            }],
            responses=[
                SentinelHubRequest.output_response(
                    'default',
                    MimeType.TIFF,
                )
            ],
            bbox=BBox(bbox, self.aoi.crs.to_epsg()),
            size=(x, y),
            config=SHConfig())

        array = request.get_data(max_threads=min(32, os.cpu_count() + 4))[0]
        if array is not None:
            return array
        else:
            return None
def get_true_colour_request(time_interval):
    return SentinelHubRequest(
        evalscript=evalscript_true_colour,
        input_data=[
            SentinelHubRequest.input_data(
                data_collection=DataCollection.SENTINEL2_L1C,
                time_interval=time_interval,
                mosaicking_order='leastCC'
            )
        ],
        responses=[
            SentinelHubRequest.output_response('default', MimeType.PNG)
        ],
        bbox=betsiboka_bbox,
        size=betsiboka_size,
        config=config
    )
Ejemplo n.º 16
0
    def test_single_tiff(self):
        """ Test downloading three bands of L1C
        """
        evalscript = """
            //VERSION=3

            function setup() {
                return {
                    input: [{
                        bands: ["B02", "B03", "B04"],
                        units: "REFLECTANCE"
                    }],
                    output: {
                        bands: 3,
                        sampleType: "FLOAT32"
                    }
                };
            }

            function evaluatePixel(sample) {
                return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02];
            }
        """

        request = SentinelHubRequest(
            evalscript=evalscript,
            input_data=[
                SentinelHubRequest.input_data(
                    data_source=DataSource.SENTINEL2_L1C,
                    time_interval=('2017-12-15T07:12:03',
                                   '2017-12-15T07:12:04'),
                    maxcc=0.8)
            ],
            responses=[
                SentinelHubRequest.output_response('default', MimeType.TIFF)
            ],
            bbox=BBox(bbox=[46.16, -16.15, 46.51, -15.58], crs=CRS.WGS84),
            size=(512, 856))

        img = request.get_data(max_threads=3)[0]

        self.assertEqual(img.shape, (856, 512, 3))
        self.test_numpy_data(img,
                             exp_min=0,
                             exp_max=2.01825,
                             exp_mean=0.29408056)
Ejemplo n.º 17
0
    def _create_response_objects(self):
        """Construct SentinelHubRequest output_responses from features"""
        responses = []
        for feat_type, feat_name, _ in self.features:
            if feat_type.is_raster():
                responses.append(
                    SentinelHubRequest.output_response(feat_name,
                                                       MimeType.TIFF))
            elif feat_type.is_meta():
                responses.append(
                    SentinelHubRequest.output_response("userdata",
                                                       MimeType.JSON))
            else:
                # should not happen as features have already been validated
                raise ValueError(f"{feat_type} not supported!")

        return responses
Ejemplo n.º 18
0
    def test_other_args(self):
        """ Test downloading three bands of L1C
        """
        evalscript = """
            //VERSION=3

            function setup() {
                return {
                    input: ["B02", "B03", "B04"],
                    sampleType: "UINT16",
                    output: { bands: 3 }
                };
            }

            function evaluatePixel(sample) {
                return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02];
            }
        """

        request = SentinelHubRequest(
            evalscript=evalscript,
            input_data=[
                SentinelHubRequest.input_data(
                    data_source=DataSource.SENTINEL2_L1C,
                    time_interval=('2017-12-15T07:12:03',
                                   '2017-12-15T07:12:04'),
                    maxcc=0.8,
                    other_args={
                        'processing': {
                            'upsampling': 'NEAREST',
                            'downsampling': 'NEAREST',
                            'atmosphericCorrection': 'NONE'
                        }
                    })
            ],
            responses=[SentinelHubRequest.output_response('default', 'tiff')],
            bbox=BBox(bbox=[46.16, -16.15, 46.51, -15.58], crs=CRS.WGS84),
            size=(512, 856),
            config=self.CONFIG,
            data_folder=self.OUTPUT_FOLDER)

        img = request.get_data(max_threads=3)[0]

        self.assertEqual(img.shape, (856, 512, 3))
        self.test_numpy_data(img, exp_min=0, exp_max=255, exp_mean=74.92)
Ejemplo n.º 19
0
    def test_bad_credentials(self):

        evalscript = """
                    //VERSION=3

                    function setup() {
                        return {
                            input: ["B02", "B03", "B04"],
                            sampleType: "UINT16",
                            output: { bands: 3 }
                        };
                    }

                    function evaluatePixel(sample) {
                        return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02];
                    }
                """
        request_params = dict(
            evalscript=evalscript,
            input_data=[
                SentinelHubRequest.input_data(
                    data_source=DataSource.SENTINEL2_L1C,
                    time_interval=('2017-12-15T07:12:03',
                                   '2017-12-15T07:12:04'),
                )
            ],
            responses=[SentinelHubRequest.output_response('default', 'tiff')],
            bbox=BBox(bbox=[46.16, -16.15, 46.51, -15.58], crs=CRS.WGS84),
            size=(512, 856))

        bad_credentials_config = SHConfig()
        bad_credentials_config.sh_client_secret = 'test-wrong-credentials'

        request = SentinelHubRequest(**request_params,
                                     config=bad_credentials_config)
        with self.assertRaises(CustomOAuth2Error):
            request.get_data()

        missing_credentials_config = SHConfig()
        missing_credentials_config.sh_client_secret = ''

        request = SentinelHubRequest(**request_params,
                                     config=missing_credentials_config)
        with self.assertRaises(ValueError):
            request.get_data()
Ejemplo n.º 20
0
def predict_on_sh(model_script, bbox, size, timestamp, config):
    request = SentinelHubRequest(
        evalscript=model_script,
        input_data=[
            SentinelHubRequest.input_data(
                data_collection=DataCollection.SENTINEL2_L1C,
                time_interval=(timestamp - dt.timedelta(minutes=5),
                               timestamp + dt.timedelta(minutes=5)),
                maxcc=1,
            )
        ],
        responses=[
            SentinelHubRequest.output_response('default', MimeType.TIFF)
        ],
        bbox=bbox,
        size=size,
        config=config)
    return request.get_data()[0]
Ejemplo n.º 21
0
 def _create_sh_request(self, time_interval, bbox, size_x, size_y):
     """ Create an instance of SentinelHubRequest
     """
     return SentinelHubRequest(
         evalscript=self.evalscript,
         input_data=[
             SentinelHubRequest.input_data(
                 data_collection=self.data_collection,
                 mosaicking_order=self.mosaicking_order,
                 time_interval=time_interval,
                 maxcc=self.maxcc,
                 other_args=self.aux_request_args)
         ],
         responses=self.responses,
         bbox=bbox,
         size=(size_x, size_y),
         data_folder=self.cache_folder,
         config=self.config)
Ejemplo n.º 22
0
 def create_request(time_interval):
     return SentinelHubRequest(
         evalscript=evalscript,
         input_data=[
             SentinelHubRequest.input_data(
                 data_collection=DataCollection.SENTINEL2_L2A,
                 time_interval=time_interval,
                 mosaicking_order='leastCC',
                 maxcc=maxcc,
             )
         ],
         responses=[
             SentinelHubRequest.output_response('default', MimeType.TIFF)
         ],
         geometry=polygon,
         bbox=bbox,
         size=size,
         config=config,
     )
def getSentinelElevation(bbox, size, date_ranges, config):
    
    
    evalscript_dem = '''
    //VERSION=3
    function setup() {
      return {
        input: ["DEM"],
        output:{
          id: "default",
          bands: 1,
          sampleType: SampleType.FLOAT32
        }
      }
    }

    function evaluatePixel(sample) {
      return [sample.DEM]
    }
    '''

    dem_request = SentinelHubRequest(
        evalscript=evalscript_dem,
        input_data=[
            SentinelHubRequest.input_data(
                data_collection=DataCollection.DEM,
                time_interval=(date_ranges[0], date_ranges[1]),
        )
        ],
        responses=[
            SentinelHubRequest.output_response('default', MimeType.TIFF)
        ],
        bbox=bbox,
        size=size,
        config=config
    )

    dem_data = dem_request.get_data()
    
    return dem_data
Ejemplo n.º 24
0
def create_batch_request(
        config: DownloadConfig,
        output_responses: List[dict],
        description: str = 'Batch request') -> SentinelHubBatch:
    """ Helper function that creates a SH batch request
    """
    LOGGER.info('Read and simplify AOI geometry')
    aoi_gdf = gpd.read_file(config.aoi_filename)
    assert aoi_gdf.crs.name == 'WGS 84'
    aoi = Geometry(aoi_gdf.geometry.values[0], crs=CRS.WGS84)
    aoi = simplify_geometry(aoi)

    LOGGER.info('\nSet up SH and AWS credentials')
    _ = set_sh_config(config)

    LOGGER.info('\nThis evalscript is executed')
    evalscript = load_evalscript()

    sentinelhub_request = SentinelHubRequest(
        evalscript=evalscript,
        input_data=[
            SentinelHubRequest.input_data(
                data_collection=config.data_collection,
                time_interval=config.time_interval,
                maxcc=config.maxcc,
                mosaicking_order=config.mosaicking_order)
        ],
        responses=output_responses,
        geometry=aoi)

    batch_request = SentinelHubBatch.create(
        sentinelhub_request,
        tiling_grid=SentinelHubBatch.tiling_grid(**config.grid_definition),
        output=SentinelHubBatch.output(
            default_tile_path=
            f's3://{config.bucket_name}/{config.tiles_path}/<tileName>/<outputId>.<format>'
        ),
        description=description)

    return batch_request
Ejemplo n.º 25
0
 def get_true_color_request(time_interval):
     return SentinelHubRequest(
         evalscript=evalscript_clm,
         #evalscript=evalscript_true_color,
         input_data=[
             SentinelHubRequest.input_data(
                 data_collection=DataCollection.SENTINEL2_L1C,
                 time_interval=time_interval,
                 mosaicking_order='leastCC')
         ],
         responses=[
             SentinelHubRequest.output_response('default',
                                                MimeType.PNG)  #,
             #{
             #    "identifier": "userdata",
             #    "format": {
             #        "type": "application/json"}
             #}
         ],
         bbox=bounding_box,
         size=(x_width, y_height),
         config=config)
Ejemplo n.º 26
0
def get_request(img, evalscript, **kwargs):
    """
    Build a query using the given
    evalscript and img.
    """

    return SentinelHubRequest(
        evalscript=evalscript,
        input_data=[
            SentinelHubRequest.input_data(
                data_collection=DataCollection.SENTINEL2_L2A,
                time_interval=img.time_interval,
                mosaicking_order='leastCC'
            )
        ],
        responses=[
            SentinelHubRequest.output_response('default', MimeType.PNG)
        ],
        bbox=img.bbox,
        size=img.size,
        config=img.user.config,
        **kwargs
    )
Ejemplo n.º 27
0
    def _create_sh_request(self, date_from, date_to, bbox, size_x, size_y):
        """Create an instance of SentinelHubRequest"""
        responses = [
            SentinelHubRequest.output_response(band.name, MimeType.TIFF)
            for band in self.requested_bands + self.requested_additional_bands
        ]

        return SentinelHubRequest(
            evalscript=self.evalscript or self.generate_evalscript(),
            input_data=[
                SentinelHubRequest.input_data(
                    data_collection=self.data_collection,
                    time_interval=(date_from, date_to),
                    mosaicking_order=self.mosaicking_order,
                    maxcc=self.maxcc,
                    other_args=self.aux_request_args,
                )
            ],
            responses=responses,
            bbox=bbox,
            size=(size_x, size_y),
            data_folder=self.cache_folder,
            config=self.config,
        )
Ejemplo n.º 28
0
def getVars():
    if request.method == 'POST':
        jsonData = request.get_json()
        longitude = float(jsonData['longitude'])
        latitude = float(jsonData['latitude'])
        distance = float(jsonData['distance'])

        coords = [(longitude - (distance / 2)), (latitude - (distance / 2)),
                  (longitude + (distance / 2)), (latitude + (distance / 2))]

        bbbox = BBox(coords, crs=CRS.WGS84)
        bsize = bbox_to_dimensions(bbbox, resolution=15)

        evalscript_clm = """
        //VERSION=3
        function setup() {
          return {
            input: ["B02", "B03", "B04", "CLM"],
            output: { bands: 3 }
          }
        }
        function evaluatePixel(sample) {
          if (sample.CLM == 1) {
            return [0.75 + sample.B04, sample.B03, sample.B02]
          } 
          return [3.5*sample.B04, 3.5*sample.B03, 3.5*sample.B02];
        }
        """

        request_true_color = SentinelHubRequest(
            evalscript=evalscript_clm,
            input_data=[
                SentinelHubRequest.input_data(
                    data_collection=DataCollection.SENTINEL2_L1C,
                    time_interval=('2020-06-01', '2020-06-30'),
                    mosaicking_order='leastCC')
            ],
            responses=[
                SentinelHubRequest.output_response('default', MimeType.PNG)
            ],
            bbox=bbbox,
            size=bsize,
            config=config)

        data_with_cloud_mask = request_true_color.get_data()

        image = data_with_cloud_mask[0]
        #print(image)

        plot_image(image, factor=1 / 255, clip_range=(0, 1))
        #  plt.show()

        imagename = "C:\\Users\desai\programs\plot2.png"
        image = cv2.imread(imagename, cv2.IMREAD_COLOR)  ## Read image file
        #print(imagename)
        print("test")

        #boundaries detects foliage from green to almost white
        boundaries = [([27, 0, 98], [252, 229, 210])]

        for (lower, upper) in boundaries:
            # create NumPy arrays from the boundaries
            lower = np.array(lower, dtype="uint8")
            upper = np.array(upper, dtype="uint8")

            # find the colors within the specified boundaries and apply
            # the mask
            mask = cv2.inRange(image, lower, upper)
            output = cv2.bitwise_and(image, image, mask=mask)

            # show the images
            cv2.imshow("images", np.hstack([image, output]))
            cv2.waitKey(0)
        #boundary2 detects water from dark blue to light

        print("here")
        boundaries2 = [([32, 0, 4], [184, 104, 112])]

        for (lower, upper) in boundaries2:
            # create NumPy arrays from the boundaries
            lower2 = np.array(lower, dtype="uint8")
            upper2 = np.array(upper, dtype="uint8")

            # find the colors within the specified boundaries and apply
            # the mask
            mask2 = cv2.inRange(image, lower2, upper2)
            output2 = cv2.bitwise_and(image, image, mask=mask2)

            # show the images
            cv2.imshow("images", np.hstack([image, output2]))
            cv2.waitKey(0)

        #counts number of pixels in the boundaries
        nPixels = np.count_nonzero(mask == 0)
        count = mask.size
        #percentage = the percentage of pixels deemed bad soil, or not able to support trees  - this could include water, dry land, etc
        percentage = nPixels / count

        nPixels2 = np.count_nonzero(mask2 == 0)
        count2 = mask2.size
        percentage2 = nPixels2 / count2
        #percentage2 = the percentage of pixels that are not deemed overcrowded by vegetation

        print("The percent of land that is deemed unpplantable for tree is: " +
              str(percentage * 100) + "%")
        print(
            "The percent of land that is not overcrowded by dense vegetation is: "
            + str(percentage2 * 100) + "%")
        if percentage > 0.9:
            return "The soil is not suitable for trees"
        if percentage2 < 0.3:
            return "There is to much vegetation to plant a tree"

        if percentage < 0.9 and percentage2 > 0.3:
            return "This land is suitable for trees"
Ejemplo n.º 29
0
        return {
            input: [{
                bands: ["B02", "B03", "B04"]
            }],
            output: {
                bands: 3
            }
        };
    }

    function evaluatePixel(sample) {
        return [sample.B04, sample.B03, sample.B02];
    }
"""

request_true_color = SentinelHubRequest(
    evalscript=evalscript_true_color,
    input_data=[
        SentinelHubRequest.input_data(
            data_source=DataSource.SENTINEL2_L1C,
            time_interval=('2020-06-12', '2020-06-13'),
        )
    ],
    responses=[SentinelHubRequest.output_response('default', MimeType.PNG)],
    bbox=betsiboka_bbox,
    size=betsiboka_size,
    config=config)
true_color_imgs = request_true_color.get_data()

plot_image(true_color_imgs[-1])
Ejemplo n.º 30
0
                bands: 3
            }
        };
    }

    function evaluatePixel(sample) {
        return [sample.B04, sample.B03, sample.B02];
    }
"""

request_true_color = SentinelHubRequest(
    evalscript=evalscript_true_color,
    input_data=[
        SentinelHubRequest.input_data(
            data_collection=DataCollection.SENTINEL2_L1C,
            time_interval=('2020-06-20', '2020-06-21'),
        )
    ],
    responses=[SentinelHubRequest.output_response('default', MimeType.PNG)],
    bbox=betsiboka_bbox,
    size=betsiboka_size,
    config=config)

true_color_imgs = request_true_color.get_data()

print(
    f'Returned data is of type = {type(true_color_imgs)} and length {len(true_color_imgs)}.'
)
print(
    f'Single element in the list is of type {type(true_color_imgs[-1])} and has shape {true_color_imgs[-1].shape}'
)