How to show only one of the clusters in Goole Earth Engine unsupervised classification - cluster-analysis

Suppose we have the following codes for unsupervised classification. My goal is to identify the water bodies across the area. How can I mask out other classes (clusters) and only map one of the clusters (water bodies)in my results:
// Load a pre-computed Landsat composite for input
var input = ee.Image('LANDSAT/LE7_TOA_1YEAR/2001');
// Define a region in which to generate a sample of the input.
var region = ee.Geometry.Rectangle(29.7, 30, 32.5, 31.7);
// Display the sample region.
Map.setCenter(31.5, 31.0, 8);
Map.addLayer(ee.Image().paint(region, 0, 2), {}, 'region');
// Make the training dataset.
var training = input.sample({
region: region,
scale: 30,
numPixels: 5000
});
// Instantiate the clusterer and train it.
var clusterer = ee.Clusterer.wekaKMeans(5).train(training);
// Cluster the input using the trained clusterer.
var result = input.cluster(clusterer);
// Display the clusters with random colors.
Map.addLayer(result.randomVisualizer(), {}, 'clusters');

I only need the cluster (0) so I could mask the rest of the classes using the codes below:
// showing only one cluster.
var subset = result.select("cluster").eq(0).selfMask();

Related

Filling Color in anychart js chart in multiple quadrant scatter chart

Im newbie in js and anychart
I have anychart chart like this
how can i fill the color based on range like risk matrix.
*Result What i want
This is my code
// create data
var data = [
{x: 2.88, value: 3.12},
{x: 1.9, value: 2.3}
];
// create a chart
var chart = anychart.scatter();
// adjust scale min/max
chart.xScale().minimum(0).maximum(5.0);
chart.yScale().minimum(0).maximum(5.0);
// divide scale by three ticks
chart.xScale().ticks().interval(1.0);
chart.yScale().ticks().interval(1.0);
// create a bubble series and set the data
var series = chart.marker(data);
// enable major grids
chart.xGrid().enabled(true).stroke('0.1 blue');
chart.yGrid().enabled(true).stroke('0.1 blue');
var yAxis = chart.xAxis();
// set the chart title
chart.title("Quadrant-like Scatter Bubble Chart");
// set the container id
chart.container("container").draw();
});```
To get a risk matrix in the result, it’s better to use the Heatmap module.
Heatmap from your screenshot is recreated in this sample here: https://playground.anychart.com/0RAcumgI/3
Did we understand your question correctly?

unmixing in earth engine and generate classification map

hello I apply unmixing on sentinel image based on the spectral signatures I provided
here is the code:
var SentinelColl = ee.ImageCollection("COPERNICUS/S2_SR")
.filterBounds(geometry)
.filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', 5)
.filterMetadata('SNOW_ICE_PERCENTAGE','less_than',5)
.filterDate('2020-01-01', '2022-01-01')
.sort('system:index',false)
.select('B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8','B8A','B11','B12')
.median()
var classNames = Urban.merge(Water).merge(Forest).merge(AgricultureWet).merge(AgricultureDry).merge(MinesNew)
//.merge(shadow).merge(barren)//.merge(roadL1).merge(roadL2);
var bands = Sentinel.bandNames();
var training = Sentinel.sampleRegions({
collection: classNames,
properties: ['landcover'],
scale: 10
});
var fractions = Sentinel.clip(geometry).unmix([mineSP, agrWSP,agrDSP,waterSP,forsSP,urbSP],true,true);
but how can I generate final classification map so that each pixel assigned and coded as the endmember with the max fraction?
like in ENVI: max rule classifier
I want to generate a map which each pixel assigned to one class based on the aboundance /fraction values of them
finally I will calculate the number of pixels that assigned to each class

Atmospheric correction for Sentinel-2 imagery in Google Earth Engine

I want to apply atmospheric correction on Sentinel-2 imagery in Google Earth Engine(GEE). I saw the Sammurphy code which is written in Python and unfortunately it did not work for me. I tried the dark pixel subtraction method using the code(Java) below but it results in a total dark image over my region of interest.
I am new to both Earth Engine and JavaScript. Has anyone tried using the dark pixel subtraction or any other atmospheric correction on Sentinel 2 imagery in GEE (preferably a code written in Java)?
var toa=maskedComposite1;
var thresh= 0.5;
var dark=findDarkPixels(toa, thresh)
print(dark);
//Function to find dark pixels from threshold on sum of NIR, SWIR1, & SWIR2 bands
//Returns classified image with binary [0,1] 'dark' band
// toa: Sentinel 2 image converted to surface radiance
// thresh: threshold (0.2 - 0.5) value for sum of NIR, SWIR1 & SWIR2 bands
function findDarkPixels(toa, thresh) {
var darkPixels1 = toa.select(['B8','B11','B12']);
var darkPixels = darkPixels1.reduce(ee.Reducer.sum()).lt(thresh);
var filtered = darkPixels.focal_mode(0.1, 'square', 'pixels');
Map.addLayer(filtered,{},'darkPixel');
return filtered.rename(['dark']);
}
If you do not need specific atmospheric correction then you can use the Level-2A Sentinel-2 data already available in GEE. Here is the link to dataset info. The atmospheric correction for this data set is performed by sen2cor. Note the time period the data are available for as Level-2A data is not available for the entire data archive.

TPU training freezes in the middle of training

I'm trying to train a CNN regression net in TF 1.12, using TPU v3-8 1.12 instance. The model succesfully compiles with XLA, starting the training process, but some where after the half iterations of the 1t epoch freezes, and doing nothing. I cannot find the root of the problem.
def read_tfrecord(example):
features = {
'image': tf.FixedLenFeature([], tf.string),
'labels': tf.FixedLenFeature([], tf.string)
}
sample=tf.parse_single_example(example, features)
image = tf.image.decode_jpeg(sample['image'], channels=3)
image = tf.reshape(image, tf.stack([540, 540, 3]))
image = augmentation(image)
labels = tf.decode_raw(sample['labels'], tf.float64)
labels = tf.reshape(labels, tf.stack([2,2,45]))
labels = tf.cast(labels, tf.float32)
return image, labels
def load_dataset(filenames):
files = tf.data.Dataset.list_files(filenames)
dataset = files.apply(tf.data.experimental.parallel_interleave(tf.data.TFRecordDataset, cycle_length=4))
dataset = dataset.apply(tf.data.experimental.map_and_batch(map_func=read_tfrecord, batch_size=BATCH_SIZE, drop_remainder=True))
dataset = dataset.apply(tf.data.experimental.shuffle_and_repeat(1024, -1))
dataset = dataset.prefetch(buffer_size=1024)
return dataset
def augmentation(img):
image = tf.cast(img, tf.float32)/255.0
image = tf.image.random_brightness(image, max_delta=25/255)
image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
image = tf.image.per_image_standardization(image)
return image
def get_batched_dataset(filenames):
dataset = load_dataset(filenames)
return dataset
def get_training_dataset():
return get_batched_dataset(training_filenames)
def get_validation_dataset():
return get_batched_dataset(validation_filenames)
The most likely cause is an issue in the data pre-processing function, take a look at the troubleshooting documentation Errors in the middle of training, it could be helpful to get a guidance.
I did not catch anything strange with your code.
Are you using Cloud Storage Buckets to work with those images and files? If yes, Are those buckets in the same region?
You might use Cloud TPU Audit Logs to determine if the issue is related with the resources in the system or how you are accessing your data.
Finally I suggest you to take a look in the Training Mask RCNN on Cloud TPU
documentation.

How can I find all the lakes in a region (bounded by polgon) in earth engine?

The problem statement is that a region of interest is given.
I need to find all the lakes in a polygon bounded region using the NDWI index for water bodies, which are at a height of more than 1500m. Then display the changes in the area of lake's surface water starting from the year 1984 till 2018 on a 2-year interval in a table like structure in Google Earth Engine. I have used Landsat 5 and 7 data.
I have created the following code:
Earth Engine Code
Now I need to display the results in the polygon marked region in a table sort of structure in the following format:-
Rows - (Lake 1, Lake 2, Lake 3... Lake n)
Columns - (Surface Area in 1984, Surface Area in 1986, ....2018)
How should I go about doing it?
I answer this question in regard of the code posted in the comments, hopefully the question is updated with the code posted in the comments.
Filtering: ok.
Just a comment, I wouldn't name an image collection variable with name img, it's just confusing to me, but variables names are up to you.
var mf = ee.Filter.calendarRange(10, 12, 'month');
var img1 = ee.ImageCollection(l5
.filterDate('1984-01-01','1999-12-31')
.filterBounds(roi)
.filter(mf));
var img2 = ee.ImageCollection(l7
.filterDate('2000-01-01','2018-12-31')
.filterBounds(roi)
.filter(mf));
add NDWI: This is your code:
var addNDWI = function(image){
var ndwi = image.normalizedDifference(['B2', 'B4']).rename('NDWI');
var ndwiMask = ndwi.gte(0.3);
return image.addBands(ndwi);
};
var image1 = img1.map(addNDWI);
var image2 = img2.map(addNDWI);
you are not saving ndwiMask, so you won't be able to use it outside of this function. Again, I wouldn't name them image as they are not images but image collections.
elevation mask: you have to select the elevation band:
var elevMask = elevation.select('elevation').gt(1500)
This mask image will have ones where elevation is greater than 1500 and zeros where not.
applying masks: in this part you have to remember that Earth Engine uses functional programming, so objects are not mutable, this means that you cannot update the state of an object using a method, you have to catch the output of the method you are calling. Here you need ndwi mask, so you have to compute it with NDWI band.
var mask = function(image){
var ndwiMask = image.select('NDWI').gt(0.3)
var ndwi_masked = image.updateMask(ndwiMask);
return ndwi_masked.updateMask(elevMask);
};
var maskedImg = image1.map(mask); // ImageCollection!
var maskedImg2 = image2.map(mask); // ImageCollection!
Visualizing: As the results are ImageCollection, when you add it to the map EE makes a mosaic and that is what you would see. Keep that in mind for further processing.
var ndwiViz = {bands: ['NDWI'], min: 0.5, max: 1, palette: ['00FFFF', '0000FF']};
Map.addLayer(maskedImg, ndwiViz, 'Landsat 5 masked collection');