Part 14: Spectral and Temporal Analysis (3)
Chapter 3: Downloading Annual Composite Image Thumbnails
3.1 Obtain the Bounding Area for Thumbnails
import ee
import geemap
ee.Initialize()
Map = geemap.Map(basemap='HYBRID')
# Create a geometry and attribute for the ROI
roi = ee.Feature(ee.Geometry.Point([107.581742, 22.33334]), opt_properties={'LandCover': 'Eucalyptus'})
# Get the minimum bounding rectangle with a buffer
bound = roi.geometry().buffer(1500).bounds()
# Display the ROI on the map
Map.addLayer(bound, {}, 'roi_bound')
Map.centerObject(roi, 14)
Map
3.2 NDVI Vegetation Index Function
def addNDVI(img):
return img.addBands(img.normalizedDifference(['nir', 'red']).rename('NDVI'))
3.3 Function to Get Annual Composite Images
def get_year_mvc(year):
# Cloud removal
imgs = pyeepkg.Landsat().get_readyDat_Landsat5789_C2L2SR(
bound=bound,
yearS=year,
yearE=year,
clip_with_bound=True
)
# Calculate NDVI for each image
with_ndvi = imgs.map(addNDVI)
# Return the median composite image with NDVI and set the year as an attribute
return with_ndvi.select(['swir1', 'nir', 'red', 'NDVI']).median().set("Year", year).set('system:time_start', ee.Date.fromYMD(year, 7, 1).millis())
# Example of running the function for a single year (for testing)
img20 = get_year_mvc(2020)
Map.addLayer(img20, {'bands': ['swir1', 'nir', 'red']}, 'img20')
img20

3.5 Running the Function for Multiple Years
# Define the range of years
years = range(1991, 2021)
# Create a list of annual composite images
imgs = ee.ImageCollection([get_year_mvc(y) for y in list(years)])
# Check the number of images
imgs.size().getInfo()
# Set visualization parameters
vis_params = {'bands': ['swir1', 'nir', 'red'], 'min': 0.0, 'max': 0.4}
Map.addLayer(img20, vis_params, 'img20')
3.6 Create New Directory
import os
# Set display parameters
vis_params = {'bands': ['swir1', 'nir', 'red'], 'min': 0, 'max': 0.40}
# Define the output directory
out_dir = '../Figures/Dync'
# Check if the directory exists, create it if not
if not os.path.exists(out_dir):
os.mkdir(out_dir)
# Define file names with prefix "Y"
names = ['Y' + str(y) for y in list(years)]
3.7 Download Thumbnails
import geemap
# Download thumbnails for each annual composite image
geemap.get_image_collection_thumbnails(
ee_object=imgs.select(['swir1', 'nir', 'red']),
out_dir=out_dir,
vis_params=vis_params,
names=names,
region=bound,
dimensions=300
)
3.8 List Existing Files
lsdir = [out_dir + '/' + t for t in os.listdir(out_dir)]
lsdir
3.9 Get Thumbnail Sizes
from PIL import Image
# Open images and get their sizes
images = [Image.open(x) for x in lsdir]
widths, heights = zip(*(i.size for i in images))
print(widths, heights)
3.10 Calculate Total Width and Height
# Calculate total width and height for the composite image
columns, rows, gap = 10, 3, 5
total_width = max(widths) * columns + gap * columns
total_height = max(heights) * rows + gap * rows
print(total_width, total_height)
3.11 Create Composite Image
import os
from PIL import Image, ImageFont, ImageDraw
# Directory containing thumbnails
dir_thumbs = "../Figures/Dync/"
# Define the number of columns, rows, and the gap between images
columns, rows, gap = 10, 3, 5
# Calculate the total width and height of the composite image
total_width = max(widths) * columns + gap * columns
total_height = max(heights) * rows + gap * rows
# Set initial positions
x_offset, y_offset, halfw = 0, 0, 10
# Specify font for drawing text on the image
font = ImageFont.truetype(r'C:\Users\System-Pc\Desktop\arial.ttf', 40)
# Create a new image for the composite
new_im = Image.new('RGB', (total_width, total_height))
# Iterate over the thumbnails
for im in images:
draw = ImageDraw.Draw(im)
# Add text (year) to each thumbnail
draw.text(xy=(20, 20), text=os.path.basename(im.filename)[1:5], fill="blue", align="left", font=font)
# Draw a red rectangle in the center of each thumbnail
draw.rectangle(xy=[im.size[0]/2-halfw, im.size[1]/2-halfw, im.size[0]/2+halfw, im.size[1]/2+halfw], outline='red', width=3)
# Paste the thumbnail onto the composite image
new_im.paste(im, box=(x_offset, y_offset))
# Update the x and y offsets for the next thumbnail
x_offset += im.size[0] + gap
if x_offset >= total_width:
x_offset = 0
y_offset += im.size[1] + gap
# Save the composite image
fNameMed = '../Figures/Thumbnails_Y1991_2020_Years_Med.png'
new_im.save(fNameMed)
new_im.close()
Last updated