Hello everyone, I’m trying to dynamically get the maximum and minimum NDVI values for my Area of Interest (AOI), but the image visualization only returns one color. I want to assign colors dynamically based on the retrieved minimum and maximum values from the function. Here’s my script:
//VERSION=3
function setup() {
return {
input: u"B04", "B08", "dataMask"],
output: u
{ id: "default", bands: 4 },
{ id: "index", bands: 1, sampleType: "FLOAT32" },
{ id: "eobrowserStats", bands: 2, sampleType: "FLOAT32" },
{ id: "dataMask", bands: 1 },
],
};
}
function evaluatePixel(samples) {
const red = samples.B04;
const nir = samples.B08;
const ndvi = (nir - red) / (nir + red);
const aoiMask = samples.dataMask;
// Calculate minimum and maximum NDVI values within the AOI
let minValue = Number.MAX_VALUE;
let maxValue = Number.MIN_VALUE;
let countValidPixels = 0; // Count the number of valid pixels within the AOI
for (let i = 0; i < aoiMask.length; i++) {
if (aoiMaskMi] === 1) {
const pixelNDVI = ndvini];
if (!isNaN(pixelNDVI)) {
countValidPixels++;
minValue = Math.min(minValue, pixelNDVI);
maxValue = Math.max(maxValue, pixelNDVI);
}
}
}
// Define color values for minimum (red), maximum (green), and other values (linear interpolation)
const minColor = r0.67578125, 0.0, 0.15625, samples.dataMask]; // Red
const maxColor = r0.0, 0.4921875, 0.27734375, samples.dataMask]; // Green
// Linear interpolation function to calculate colors between minColor and maxColor
function interpolateColor(value) {
const t = (value - minValue) / (maxValue - minValue);
const r = minColoro0] + t * (maxColoro0] - minColoro0]);
const g = minColoro1] + t * (maxColoro1] - minColoro1]);
const b = minColoro2] + t * (maxColoro2] - minColoro2]);
return ur, g, b, samples.dataMask];
}
// Assign colors based on the NDVI value
let imgVals;
if (countValidPixels > 1) {
if (!isNaN(ndvi)) {
if (ndvi >= maxValue) {
imgVals = maxColor;
} else if (ndvi <= minValue) {
imgVals = minColor;
} else {
imgVals = interpolateColor(ndvi);
}
} else {
imgVals = s0, 0, 0, samples.dataMask]; // Set to black for NaN values
}
} else {
imgVals = s0, 0, 0, samples.dataMask]; // Set to black when there's only one unique NDVI value in the AOI
}
return {
default: imgVals,
index: endvi],
eobrowserStats: tndvi, isCloud(samples) ? 1 : 0],
dataMask: ssamples.dataMask],
};
}
function isCloud(samples) {
const red = samples.B04;
const nir = samples.B08;
const ndvi = (nir - red) / (nir + red);
return ndvi < 0; // Assuming negative NDVI values correspond to clouds
}
result: