0

I am trying to clip MODIS Land Surface Temperature in Python for a defined extent. Even though the files have been clipped, the size (X x Y) of the new file is changed. So when I plot the new data, the location of the raster is now distorted.

from pyhdf.SD import SD, SDC
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import rioxarray
import xarray as xr 

#Function to Extract Date
def extract_date(filename):
    # Extract the year and Julian day
    year = int(filename[9:13])
    julian_day = int(filename[13:16])
    
    # Convert Julian day to a Gregorian date
    date = datetime(year, 1, 1) + timedelta(days=julian_day - 1)
    
    return date

# Open the HDF4 file
file_path = 'MOD11C3.A2021001.061.2021043155222.hdf'  # replace with your file path
hdf_file = SD(file_path, SDC.READ)

date = extract_date(file_path)
print(date)
# Explore the file structure
datasets_dict = hdf_file.datasets()
print("Datasets in the HDF4 file:")
for idx, sds in enumerate(datasets_dict.keys()):
    print(idx, sds)

# Read a specific dataset
dataset_name = 'LST_Day_CMG'  # example dataset name, replace as needed
sds_obj = hdf_file.select(dataset_name)
data = sds_obj[:]
data = data*0.02
data = np.ma.masked_where(data == 0, data)  # Mask invalid data (e.g., 0 or any specific fill value)

aoiBounds = (73,21,92,32)  #West, South, East, North
#Clip HDF file
# Define the clipping extents
x_start, x_end = 1460, 1840 #converted West and East to the corresponding position of 'data'which is of 0.05 degree resolution. Eg. 73/0.05 = 1460 
y_start, y_end = 420, 640
# Extract the subset of the data
clipped_data = data[y_start:y_end, x_start:x_end]
# Path for the new HDF file
new_file_path = 'clipped_data.hdf'
# Process and visualize the data
plt.figure(figsize=(10, 6))
plt.imshow(data, cmap='jet')
plt.colorbar()
plt.title('MODIS LST Day CMG')
plt.show()

0

Browse other questions tagged or ask your own question.