Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
46 views
17 pages
Image Segmentation With Kmeans
Uploaded by
Ha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save Image Segmentation With Kmeans For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
46 views
17 pages
Image Segmentation With Kmeans
Uploaded by
Ha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save Image Segmentation With Kmeans For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save Image Segmentation With Kmeans For Later
You are on page 1
/ 17
Search
Fullscreen
acgeospatial Freelance” and Consultant in GIS, Earth Observation, Computer Vision, Machine Learning, Python, Data Anabcs k-means in Python 3 on Sentinel 2 data 6th July 201818 months ago | wrote about unsupervised classification of randomly extracted point data from satelite data, | have been meaning to follow it up with showing how straightforward itis to use the cluster algorithms in Sklearn to classify Sentinel 2 data. | have made this blog into a Juypter Notebook which is available here. Setup To run an unsupervised classification on satellite data using Python you need GDAL, Numpy and Sklearn. If you wish to see the data you will also need Matplotlib. Assuming you have the libraries installed, import them at the start.import nungy a8 np from sklearn inport cluster from osgeo import gdal, gdal_array import matplotlib.pyplot as plt 4 Tell GOAL to throw Python exceptions, and register all drivers geal .UseExceptions() geal allRegister() Running a classification on a single band Let's start by looking at a single band of Sentinel 2. In this example | am looking at band 2, which is the blue band and has a spatial resolution of 10m. Sentinel 2 is currently a pair of multispectral satellites with a variety of spatial resolutions. You can find out more about Sentinel 2 here, In this example | am using a DOS atmospherically corrected Sentinel 2a dataset over the south of England. To read it into gdal and then to convert to an array use the following code: 4 Read in raster inage {img_ds = gdal.open('../S2_may_South_coast.tif', gdal.6k Readonly) band = ing_ds.GotRastersand(2) ing = band.Readksarray()Remember | am working with band 2 (hence the second line), The variable img is now a numpy array. The shape of the array inthis, example is (519, 751). You can find this out by printing img shape()to the command line. To use the classifier we need to reshape this array. For the classifier to accept the data we need to use the command .reshape(-1,1) and that means we want to flatten the data into the rows (unknown length) and keep the coloumns as 1. So our resulting array takes the form (rows, 1). In our case this is (389769, 1) The code to do this is shown below: X = Ang.reshape((-1,1)) Now we can run the k-means classifier on our data. First ofall we need to choose how many clusters; in this case | am selecting eight lasses, Then | am fitting ito my data 0%) which we defined above, Finally | am assigning a new variable to the results ofthis fitting the dimensions of my original image. called X_Cluster. After the labels have been assigned I then need to reshape this result bac neans = cluster. kMeans(n_clusters~8) means. fit(X) X.cluster = k neans-labels_ XLcluster = X cluster. reshape (ing. shape) Finally to visualise this data use the final three lines of code: lt. Figure(Figsize-(20,20)) plt.inshow(X_cluster, cmap="hsv") plt.show()This is setting the figsize, assigning the data to plot and s ting a colour map; in this case ‘hsv, but you can choose any from here, The resulting image looks like this: Running a classification on all the bands Sentinel 2 has 13 spectral bands, giving us another 12 inputs int our classifer. It would seem a waste to not utile al of these. They do have a variety of spatial resolutions but numpy can handle that. Let's reload our image and this time read all the bands into an array.4 Read in raster dnage {img_ds = gdal.open(’../S2_may_South_coast.tif', gdal Gk Readonly) Img = np.zeros((ing_ds.RasterSize, ing_ds.RasterxSize, Ing ds.Rastercount), .2601_array.GDAL TypeCodeToNuner icTypeCode(ing_ds .GetAasterBand(1).Datatype)) for b in range(ing.shape[2]). inet: tb] ing_ds.GetRasterBand(b + 1) .ReadAsArray() The frst Ine is the same as before. The second line is the quickest way of loading a multi-band image into a numpy. This is done by intitalising an array of zeros (or it could be ones with the np,ones command). It takes parameters of the RasterYSize, RasterXSize and number of bands of the input satelite image and the data type. You can print these if unsure of the values. Then | loop over the number of bands in the image (Img shapel2), inserting the values into the numpy array. Next we need to reshape ‘our array. Similar to before but we need to keep the columns as 13 this time (img,shape{2)). So, we use the following code: new_shape = (ing-shape[@] * ing-shape[1], ing-shape[2}) ‘Again, if in doubt, print the variables to the command line. Then, based on this shape, we can build the input value X: X = degl:, :, 123] reshape(new_snape)Now we can reuse the clustering code to run the classifer as before, The only difference isthe final line that reshapes the result to a single band image, as opposed to a 13 band image neans = cluster. kMeans(n_clusters-8) neans. f3t(X) X.cluster ~ k means. labels_ X cluster = x cluster.reshapetingl:, :, 0]-shape) Use the same code to plot the data as before, shown below: pit. Figure(Figsize=(20,20)) plt.inshow(X_cluster, emap="hsv") plt.show() The result looks like the image below:This seems like an improved result compared to the result of the classification using the single band image. One of the really nice things about this code is how you can change the classifier. So, for example, if you wanted to use the Mini-Batch K-Means clustering algorithm once the data was loaded, you would only need to change one line (the first one shown below}: Ne_XMeans = cluster. MiniBatchkieans(n_clusters=8) Ne_xeans.#46(X) X.cluster = #8 kMeans.2abels_X.cluster = x cluster-reshape(ingl:, 15 0]-shape) The resulting image is shown here: This is a much faster implementation of K-Means and has produced a comparable result, though perhaps with alittle more noise, Saving your classificationFinally let's save the result as a geotiff, We do this by first opening the input image to get at its properties, We only need a single band as before (band 2). We convert it to an array of data (line 3) and then extract the columns and rows to a lis (line 4). Set the output as a geotiff (ine 5 and 6) Line 7 creates the output raster with the dimensions of the input raster; lines 8 and 9 set the projection and extent of the dat The last step is to write the classification result to a single band raster image (line 10) before calling FlushCache() to remove from memory and delete the data. és = gdal.open(. ./52_nay_Sou coast. tif") band és.GetRasterand(2) arr = band.ReadAsarray() [cols, rows] = are.shape format = “oritf™ driver = gdal. GetDriversyNane (format) outbataRaster = driver.create(".../k means gtif", rows, cols, 1, géal.GoT_Byte) outbatakaster SexGeoTransfona(ds.GetGeotransform())#asets same geotransfore as input outbataRaster, SetProjection(ds.GetProjection())#Hsets same projection as input outbataRaster. GetRasterSand(1).knitenrray(X_cluster)outDataRaster.FlushCache() ## renove fron nenory del outbataRaster ## delete the data (not the actual geotiff) That's it. You should be able to load this classification raster into a GIS package now and compare directly with your input satellite image. Recap. © We have loaded single and a mult-band raster to a numpy array © We have reshaped our data to fit the classifier © We have run the clasifer and then changed the lassifer and run again © We have displayed the results in matplotib © We have saved the results as a geotiff to use in a GIS package of choice. The code is available here as a jupyter notebook, This code shows how to use an unsupervised classification on satellite data with Python. | teach how to adapt this code to build a supervised classifications on satellite imagery with Python. Ifyou want to find out more please drop me a line or look on my website, lam a freelancer able to help you with your projects. | offer consultancy, training and writing. 'd be delighted to hear from you. Please check out the books | have written on QGIS 3.4 bnttps:/Amw.packtpub com/application-development/learn-agis-fourth-edition‘tpsv//wwwpacktoub com/application-development/agis-quick-start-quide | have grouped all my previous blogs (technical stuff / tutorials / opinions / ideas) at htt pulsisacgeos Feel free to connector follow me; 1am always keen to talk about Earth Observation. am (@map andrew on twitter Tags: [ Earth Observation Contact About Podcast Taaining Clients Contact me Book Python Course info 2022 Contact me Contact meSearch for. Recent Comments Archives ‘August 2022 July 2022 June 2022 May 2022 April 2022 December 2021 July 2021 January 2021 December 2020 October 2020 July 2020, June 2020, May 2020 April 2020 January 2020 December 2019October 2019 August 2019 July 2019 June 2019 May 2019 April 2019, March 2019 February 2019 January 2019 December 2018 November 2018 October 2018 September 2018 August 2018 July 2018, June 2018 May 2018 Apel 2018, March 2018 February 2018 January 2018 December 2017 November 2017October 2017 September 2017 ‘August 2017 July 2017 June 2017 May 2017 Apri 2017 March 2017 February 2017 January 2017 December 2016 November 2016 October 2016 September 2016 August 2016 July 2016 June 2016 May 2016 Neve | Powered by WordPress
You might also like
Chapter 1 Exploring Rasterio
PDF
100% (1)
Chapter 1 Exploring Rasterio
5 pages
Image Segmentation in Python - Practical Hands-On
PDF
No ratings yet
Image Segmentation in Python - Practical Hands-On
24 pages
Machine Learning Classification in Qgis
PDF
No ratings yet
Machine Learning Classification in Qgis
17 pages
Cheat Sheet-Building Unsupervised Learning Models
PDF
No ratings yet
Cheat Sheet-Building Unsupervised Learning Models
3 pages
RS T9 Classification
PDF
No ratings yet
RS T9 Classification
61 pages
Chapter 4
PDF
No ratings yet
Chapter 4
30 pages
Machine Learning in Remote Sensing - LinkedIn PDF
PDF
No ratings yet
Machine Learning in Remote Sensing - LinkedIn PDF
7 pages
Tutorial de Clasificación Supervisada de Imágenes de Satétite Con QGIS y R Statistics
PDF
No ratings yet
Tutorial de Clasificación Supervisada de Imágenes de Satétite Con QGIS y R Statistics
21 pages
Data Science Analysis Final Project
PDF
No ratings yet
Data Science Analysis Final Project
10 pages
Lecture 5 - App. RS
PDF
No ratings yet
Lecture 5 - App. RS
27 pages
Paper 3
PDF
No ratings yet
Paper 3
7 pages
From Import Import As Import As From Import From Import From Import From Import
PDF
No ratings yet
From Import Import As Import As From Import From Import From Import From Import
9 pages
Cluster Analysis in Python Chapter4 PDF
PDF
No ratings yet
Cluster Analysis in Python Chapter4 PDF
30 pages
Class Notes6 F24
PDF
No ratings yet
Class Notes6 F24
42 pages
Image Classification
PDF
No ratings yet
Image Classification
56 pages
Lecture 13 - Unsupervised Learning, PCA ICA
PDF
No ratings yet
Lecture 13 - Unsupervised Learning, PCA ICA
50 pages
Chapter Final Chapter
PDF
No ratings yet
Chapter Final Chapter
65 pages
ML Python Exercises UOM BDS Cluster Analysis
PDF
No ratings yet
ML Python Exercises UOM BDS Cluster Analysis
8 pages
ML0101EN Clus DBSCN Weather Py v1
PDF
No ratings yet
ML0101EN Clus DBSCN Weather Py v1
16 pages
Exp 6
PDF
No ratings yet
Exp 6
10 pages
10 Chapter5
PDF
No ratings yet
10 Chapter5
47 pages
Digital Image Classification
PDF
No ratings yet
Digital Image Classification
33 pages
Report Practical 3 Remote Sensing
PDF
No ratings yet
Report Practical 3 Remote Sensing
27 pages
L5 Classification
PDF
No ratings yet
L5 Classification
43 pages
K-Means Algorithm
PDF
No ratings yet
K-Means Algorithm
29 pages
Os5 Slides
PDF
No ratings yet
Os5 Slides
24 pages
4 Clustering With K-Means - Kaggle
PDF
No ratings yet
4 Clustering With K-Means - Kaggle
9 pages
Experiment 4 1
PDF
No ratings yet
Experiment 4 1
4 pages
Gate Exam Preparation
PDF
No ratings yet
Gate Exam Preparation
41 pages
Geog 325 Lab 7
PDF
No ratings yet
Geog 325 Lab 7
11 pages
K.means Clustering
PDF
No ratings yet
K.means Clustering
8 pages
Baidurya Debnath 4
PDF
No ratings yet
Baidurya Debnath 4
37 pages
Chapter 3 Plotting and Visualizing Your Data
PDF
No ratings yet
Chapter 3 Plotting and Visualizing Your Data
14 pages
Chapter 5 Classification of Land Cover
PDF
No ratings yet
Chapter 5 Classification of Land Cover
13 pages
12.6 Advanced Analysis and Classification
PDF
No ratings yet
12.6 Advanced Analysis and Classification
21 pages
Image Classification With RandomForests in R
PDF
No ratings yet
Image Classification With RandomForests in R
49 pages
SE KMeansClustering
PDF
No ratings yet
SE KMeansClustering
21 pages
Remote Sensing Classification Methods
PDF
No ratings yet
Remote Sensing Classification Methods
47 pages
Image Classification Tools in
PDF
No ratings yet
Image Classification Tools in
1 page
Gi 225: Remote Sensing Applications 2020/2021: Feature Extraction Classification
PDF
No ratings yet
Gi 225: Remote Sensing Applications 2020/2021: Feature Extraction Classification
40 pages
Lab 3 DCG40163 01dgu20f2019
PDF
No ratings yet
Lab 3 DCG40163 01dgu20f2019
31 pages
2015 Hyperspectral Image Classification With Limited Labeled Training Samples Using Enhanced Ensemble Learning and Conditional Random Fields
PDF
No ratings yet
2015 Hyperspectral Image Classification With Limited Labeled Training Samples Using Enhanced Ensemble Learning and Conditional Random Fields
12 pages
Classification Performances of Data Mining Clustering Algorithms For Remotely Sensed Multispectral Image Data
PDF
No ratings yet
Classification Performances of Data Mining Clustering Algorithms For Remotely Sensed Multispectral Image Data
4 pages
Lecture 12 - Unsupervised Learning - Shoould Be Marged
PDF
No ratings yet
Lecture 12 - Unsupervised Learning - Shoould Be Marged
31 pages
MSC Conservation/Facs 2010 Remote Sensing Module: Lecture 3 Thematic Information: Multispectral Classification
PDF
No ratings yet
MSC Conservation/Facs 2010 Remote Sensing Module: Lecture 3 Thematic Information: Multispectral Classification
33 pages
Rs Qgis 4 Classifications
PDF
No ratings yet
Rs Qgis 4 Classifications
16 pages
Classification of Image: Dr. Prashanth J Assistant Professor Dept. of Civil Engineering NIT Silchar
PDF
No ratings yet
Classification of Image: Dr. Prashanth J Assistant Professor Dept. of Civil Engineering NIT Silchar
28 pages
Shoreline Extraction Tutorial
PDF
No ratings yet
Shoreline Extraction Tutorial
25 pages
HW3 Processing Steps
PDF
No ratings yet
HW3 Processing Steps
17 pages
Classifying Landsat
PDF
No ratings yet
Classifying Landsat
8 pages
K9HGCI - Water Quality in Chesapeake Bay
PDF
No ratings yet
K9HGCI - Water Quality in Chesapeake Bay
17 pages
MHRS Lab Tutorial
PDF
No ratings yet
MHRS Lab Tutorial
7 pages
Remote Sensing Image Analysis With R: Aniruddha Ghosh and Robert J. Hijmans
PDF
No ratings yet
Remote Sensing Image Analysis With R: Aniruddha Ghosh and Robert J. Hijmans
49 pages
Simple Image Classification Using Raster Calculator: Work Flow
PDF
No ratings yet
Simple Image Classification Using Raster Calculator: Work Flow
4 pages
Machine Learning in Remote Sensing Data Processing
PDF
No ratings yet
Machine Learning in Remote Sensing Data Processing
6 pages
Image Classification: Unsupervised
PDF
No ratings yet
Image Classification: Unsupervised
15 pages
028 Sup Class
PDF
No ratings yet
028 Sup Class
2 pages
K-Means in Python - Solution
PDF
No ratings yet
K-Means in Python - Solution
6 pages
Unsupervised Classification
PDF
No ratings yet
Unsupervised Classification
25 pages