File size: 4,943 Bytes
5c718d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import io
import requests
import ee
import numpy as np
import matplotlib.pyplot as plt

#Initialize
service_account = '[email protected]'
credentials = ee.ServiceAccountCredentials(service_account, '.private-key.json')
ee.Initialize(credentials)

#delete clouds
def maskS2clouds(image):
        qa = image.select('QA60');

    #   // Bits 10 and 11 are clouds and cirrus, respectively.
        cloudBitMask = 1 << 10;
        cirrusBitMask = 1 << 11;

    #   // Both flags should be set to zero, indicating clear conditions.
        mask = (qa.bitwiseAnd(cloudBitMask).eq(0))and(qa.bitwiseAnd(cirrusBitMask).eq(0))

        return image.updateMask(mask).divide(10000);


#find ee_img
def extract_ee_img(location,start_date,end_date, width = 0.01 , len = 0.01) :
    """Extract the earth engine image



    Args:

        location (list[float]): 

        start_date (str): the start date for finding an image

        end_date (str): the end date for finding an image

        width (float, optional): _description_. Defaults to 0.01.

        len (float, optional): _description_. Defaults to 0.01.



    Returns:

        _type_: _description_

    """
    # define the polygone
    polygone =[[[float(location[0])-0.01,float(location[1])+0.01],
                [float(location[0])-0.01,float(location[1])-0.01],
                [float(location[0])+0.01,float(location[1])-0.01],
                [float(location[0])+0.01,float(location[1])+0.01],
    ]]    

    #define the ee geometry 
    geometry = ee.Geometry.Polygon(polygone, None, False);

    #extract the dataset
    dataset = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED')\
        .filterDate(start_date, end_date)\
        .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',1))\
        .map(maskS2clouds)
    return dataset.mean(), geometry



# Get URL
def get_url(ee_img, geometry, scale=5):
    """Get the url of a dataset and a geometry 



    Args:

        ee_img (ee.ImageCollection: meta data on the image 

        geometry (ee.Geometry.Polygon): geometry of the desired landscape

        scale (int, optional): _description_. Defaults to 5.



    Returns:

        str: the url to use to ask the server

    """
    region = geometry

    # collectionList = ee_img.toList(ee_img.size())
    # collectionSize = collectionList.size().getInfo()
    # for i in xrange(collectionSize):
    #     ee.batch.Export.image.toDrive(
    #         image = ee.Image(collectionList.get(i)).clip(rectangle), 
    #         fileNamePrefix = 'foo' + str(i + 1), 
    #         dimensions = '128x128').start()

    url = ee_img.getDownloadURL({
        # 'min': 0.0,
        # 'max': 0.3,
        'bands': ['B4', 'B3', 'B2'],
        'region' : region,
        'scale' : scale,
        'format' : 'NPY'
    })
    
    return url

def extract_np_from_url(url):
    """extract a numpy array based on a url



    Args:

        url (str): _description_



    Returns:

        numpyarray: response from earth engine as numpy

    """
    #get the response from url
    response = requests.get(url)

    #transform it into numpy
    data = np.load(io.BytesIO(response.content))
    
    #transform numpy of tuples to 3D numpy
    temp1 = []

    for x in data:
        temp2 = []
        for y in x :
            temp2.append([z for z in y])
        temp1.append(temp2)

    data = np.array(temp1)

    return data
    
#Fonction globale
def extract_img(location,start_date,end_date, width = 0.01 , len = 0.01,scale=5):
    """Extract an image of the landscape at the selected longitude and latitude with the selected width and length 



    Args:

        location (list[float]): [latitude of the center of the landscape, longitude of the center of the landscape]

        start_date (str): the start date  

        end_date (str): _description_

        width (float, optional): _description_. Defaults to 0.01.

        len (float, optional): _description_. Defaults to 0.01.

        scale (int, optional): _description_. Defaults to 5.



    Returns:

        img: image as numpy array

    """
    ee_img, geometry = extract_ee_img(location, width,start_date,end_date , len)
    url = get_url(ee_img, geometry, scale)
    img = extract_np_from_url(url)
    
    return img

# transform img from numpy to PIL
def transform_ee_img(img, min = 0, max=0.3):
    """Transform an img from numpy to PIL



    Args:

        img (numpy array): the original image as a numpy array 

        min (int, optional): _description_. Defaults to 0.

        max (float, optional): _description_. Defaults to 0.3.



    Returns:

        img_test: a PIL image 

    """
    img_test=img
    img_test=np.minimum(img_test*255/max,np.ones(img.shape)*255)
    img_test=np.uint8((np.rint(img_test)).astype(int))
    plt.imshow(img_test)
    return img_test