I’m new to AWS services. I’ve always used the code below to calculate NDVI for images that were located in a directory.
JavaScript
x
28
28
1
path = r'images'
2
dirContents = os.listdir(path)
3
4
for file in dirContents:
5
if os.path.isdir(file):
6
subDir = os.listdir(file)
7
8
# Assuming only two files in each subdirectory, bands 4 and 8 here
9
if "B04" in subDir[0]:
10
band4 = rasterio.open(subDir[0])
11
band8 = rasterio.open(subDir[1])
12
else:
13
band4 = rasterio.open(subDir[1])
14
band8 = rasterio.open(subDir[0])
15
16
red = band4.read(1).astype('float32')
17
nir = band8.read(1).astype('float32')
18
19
#compute the ndvi
20
ndvi = (NIR.astype(float) - RED.astype(float)) / (NIR+RED)
21
22
profile = red.meta
23
profile.update(driver='GTiff')
24
profile.update(dtype=rasterio.float32)
25
26
with rasterio.open(outfile, 'w', **profile) as dst:
27
dst.write(ndvi.astype(rasterio.float32))
28
Now all the necessary images are in an amazon S3 folder. How do I replace the lines below?
JavaScript131path = r'images'
2dirContents = os.listdir(path)
3
Advertisement
Answer
Amazon S3 is not a filesystem. You will need to use different commands to:
- List the contents of a bucket/path
- Download the files to local storage
- Then access the files on local storage
You can use the boto3
AWS SDK for Python to access objects stored in S3.
For example:
JavaScript
1
12
12
1
import boto3
2
3
s3_resource = boto3.resource('s3')
4
5
# List objects
6
objects = s3_resource.Bucket('your-bucket').objects.filter(Prefix='images/')
7
8
# Loop through each object
9
for object in objects:
10
s3_resource.Object(object.bucket_name, object.key).download_file('local_filename')
11
# Do something with the file here
12