Beispiel #1
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)
Beispiel #2
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
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
Beispiel #4
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]
Beispiel #5
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)
Beispiel #6
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]
Beispiel #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)
    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
Beispiel #9
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
Beispiel #11
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)
Beispiel #12
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
Beispiel #14
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)
Beispiel #15
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
    )
Beispiel #17
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)
Beispiel #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)
Beispiel #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()
Beispiel #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]
Beispiel #21
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
Beispiel #23
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)
Beispiel #24
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
    )
    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,
        )
Beispiel #26
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"
Beispiel #27
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])
Beispiel #28
0
    }

    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}'
)

image = true_color_imgs[0]
print(f'Image type: {image.dtype}')
    function evaluatePixel(sample) {
        return [sample.B04, sample.B03, sample.B02];
    }
"""

request_true_colour = SentinelHubRequest(
    evalscript=evalscript_true_colour,
    input_data=[
        SentinelHubRequest.input_data(
            data_collection=DataCollection.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_colour_imgs = request_true_colour.get_data()
print(f'Returned data is of type = {type(true_colour_imgs)} and length {len(true_colour_imgs)}.')
print(f'Single element in the list is of type {type(true_colour_imgs[-1])} and has shape {true_colour_imgs[-1].shape}.')

image = true_colour_imgs[0]
print(f'Image type: {image.dtype}')

# plot function
# factor 3.5 to increase brightness
Beispiel #30
0
def add_coordinates():
    filename = "picture.png"
    data = request.json
    #print(data)
    """
    leftBottomLat: 46.09728117681059
    leftBottomLng: 14.524612426757812
    rightTopLat: 46.12728117681059
    rightTopLng: 14.554612426757812
    """
    # PLS do not abuse
    CLIENT_ID = 'ec4f50ed-33c6-4e8d-806c-f6ca435c18bd'
    CLIENT_SECRET = '&E}d~KiDvRmIUmZ>fd+h_TF*mg#:g~[<bPI<ix<E'
    config = SHConfig()

    if CLIENT_ID and CLIENT_SECRET:
        config.sh_client_id = CLIENT_ID
        config.sh_client_secret = CLIENT_SECRET

    betsiboka_coords_wgs84 = [
        data_json["leftBottomLng"], data_json["leftBottomLat"],
        data_json["rightTopLng"], data_json["rightTopLat"]
    ]
    #betsiboka_coords_wgs84 = [13.430786,45.565987,15.548401,46.464349]
    #filename = #f"hi{str(sum(betsiboka_coords_wgs84))}.png"

    # GET DEM DATA
    resolution, betsiboka_bbox, betsiboka_size = get_resolution(
        betsiboka_coords_wgs84)
    dem_data = get_dem_data(betsiboka_bbox, betsiboka_size)

    rays = get_rays(center_point, dem_data)

    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_collection=DataCollection.SENTINEL2_L1C,
                time_interval=('2020-04-01', '2020-08-30'),
                mosaicking_order='leastCC')
        ],
        responses=[
            SentinelHubRequest.output_response('default', MimeType.PNG)
        ],
        bbox=betsiboka_bbox,
        size=betsiboka_size,
        config=config)

    true_color_imgs = request_true_color.get_data()
    image = true_color_imgs[0]
    print(f'Image type: {image.dtype}')

    figsize = (12, 8 * n / m)
    fig, ax = plot_image(image,
                         factor=0.017,
                         clip_range=(0, 1),
                         figsize=figsize)

    ax.set_ylim(dem_data.shape[1] - 1, 0)
    p1 = None
    for ray in rays:
        if random.random() < 0.1:
            see_ray = seeable_points_on_ray(list(ray.keys()),
                                            list(ray.values()))
            #print(see_ray)
            for p in see_ray:
                if see_ray[p] == 1:
                    p1 = p
                    #seeable.add((p[0],p[1]))
                    plt.plot(p[0], p[1], 'o', color='y', alpha=1, markersize=3)
    plt.plot(p1[0], p1[1], 'o', color='y', alpha=1, label="visible area")
    #x_seeable, y_seeable = list(map(lambda x : x[0], seeable)), list(map(lambda x : x[1], seeable))
    #plt.plot(x[:5],y[:5],'o', color='b')
    plt.plot(center_point[0],
             center_point[1],
             '*',
             color='r',
             label="our location")
    ax.legend()
    #plt.show()
    #seeable_points(z)
    plt.savefig(filename)
    return send_file("../" + filename, as_attachment=True)