import ee # Initialize Earth Engine ee.Initialize(project='farmbase-b2f7e') # Define the farm boundary as a GeoJSON geometry farm_boundary = ee.Geometry.Polygon( [ [ [75.3589059, 24.4474494], [75.3588523, 24.4469977], [75.3594504, 24.4469415], [75.3594465, 24.4468412], [75.3598378, 24.4468241], [75.3598374, 24.4467459], [75.3600919, 24.446758], [75.3602018, 24.4473412], [75.3589059, 24.4474494] ] ] ) # Define the time range for satellite imagery start_date = '2022-01-01' end_date = '2022-12-31' # Load satellite imagery (e.g., Sentinel-2) image_collection = ( ee.ImageCollection('COPERNICUS/S2') .filterBounds(farm_boundary) .filterDate(ee.Date(start_date), ee.Date(end_date)) .sort('CLOUDY_PIXEL_PERCENTAGE') .first() ) # Define a region of interest for classification roi = farm_boundary # Load the USDA NASS Cropland Data Layer (CDL) cdl = ee.Image('USDA/NASS/CDL/2021') # You can choose the year you need # Select relevant bands from the CDL cdl_bands = ['cropland'] # Sample the CDL at the farm boundary cdl_sample = cdl.select(cdl_bands).sample( region=roi, scale=30, geometries=True, ) # Define the CDL class property as 'crop_type' cdl_sample = cdl_sample.rename(['crop_type']) # Merge the CDL sample with your own training data (if available) # Replace 'training_data' with your own FeatureCollection training_data = training_data.merge(cdl_sample) # Select relevant bands from the imagery bands = ['B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B8A', 'B11', 'B12'] # Sample the imagery at training data points training = image_collection.select(bands).sampleRegions( collection=training_data, properties=['crop_type'], scale=10, ) # Define a classifier (e.g., Random Forest) classifier = ee.Classifier.randomForest(10).train( features=training, classProperty='crop_type', inputProperties=bands, ) # Classify the image classified = image_collection.select(bands).classify(classifier) # Get the crop type prediction for the farm boundary prediction = classified.reduceRegion( reducer=ee.Reducer.mode(), geometry=roi, scale=10, ) # Print the predicted crop type print('Predicted Crop Type:', prediction.get('classification'))