Pages

Showing posts with label MATLAB. Show all posts
Showing posts with label MATLAB. Show all posts

Saturday, 14 February 2015

MATLAB tutorial: Dividing image into blocks and applying a function

Often due to the limitation in memory, we want to divide an image into mxn blocks and process those blocks. If your block processing outputs an image then, you can use blockproc function in MATLAB. But, if processing function outputs points then one can’t use block processing. For that, one has to rely on image indexing to divide image into blocks. So here I will show you how you can divide image into blocks and process those individual blocks for any particular function using indexing. I am going to use block processing for finding pivot irrigation fields detection that was featured in this post. The trick is to apply matrix indexing to get chunk of block data and process them in a sequential manner. 

Here is the original image. We are going to divide it into mxn blocks. With the code you can specify any m or n value.

Original image

Block processing sequential numbering
With the following code, the block processing on individual blocks are performed. Feel free to copy the code and adapt it to your liking. Everything in the code is self-explanatory, so just go through the code line by line and you will understand whats going on.

The output of block processing for original image is as follows:

Block processing of detecting circles 

.

Wednesday, 14 January 2015

MATLAB Tutorial: Finding center pivot irrigation fields in a high resolution image

In this post, we will be talking about finding circular irrigation fields. The image was download from here. If you want to try, download it and play around. The approach I am using is detection of edges and finding edges that form circular edges. If you have heard of Hough’s transformation for detection of straight lines, the method is just an extension of it to detect circles. For Hough’s transformation, please go through here. If you have this excellent book, it has an elaborate explanation of Hough’s transformation to detect straight lines. Peoples have used Hough’s transformation for many different purpose. Many people use it for detecting straight building edges that can used to reconstruct buildings for 3-D buildings, generating city GML models etc.

For Hough’s transformation for straight line detection, you can use either PYTHON based Scikit-image or MATLAB. Circular Hough's transformation is also available in both scikit-image and openCV. The algorithm (imfindcircles) is available in MATLAB since 2013b version with image processing toolbox. I could not find the algorithm in any remote sensing software so far. My personnel view is that remote sensing software are very behind on incorporating state-of-the-art algorithms. So, knowing some coding either PYTHON, MATLAB or R will take you to greater heights in your professional path.

A circle is represented mathematically as:

(x-x_{center})^2 + (y - y_{center})^2 = r^2

where xcenter and ycenter are center of the circle and r is the radius of the circle. As you can see, there are 3 parameters to be fitted for cicular hough transformation.

Read the documentation of MATLAB, to get an idea about imfindcircles function parameters. So here basically, we are going to use imfindcircles function to detect center pivot irrigation fields in the image. In this image, there are only dark pivot circular fields surround by bright objects. So, we will be using only ‘dark’ mode of imfindcircles. The minimum circle and the maximum circle radii are image dependent so you need to provide those information with a little bit of data exploration.

Here is a code in MATLAB.

Original RGB image

RGB image with detected pivot irrigation fields
As you can see, 7 fields out of 9 fields were correctly detected. Two undetected fields( middle -top of the image) are also darker circles but due to its low contrast with surrounding, they were not detected. Even with the higher value for parameter 'sensitivity' and the low value of 'edgeThreshold' paramter, those two fields were undetected. You can further increse sensitivity and lower edgeThreshold parameters, to find those undetected circles but then you risk of finding many false alarms as well.

I have a gut feeling that with OBIA with ecognition, the process of finding center pivot irrigation fields would be not a straight forward procedure as with using the function  imfindcircles and the process would be much complex. Nevertheless, i will try it with eCognition in near future and report back.

Pixel-based based classification using any machine learning classifies will fail miserably for this case as center pivot irrigation fields ares spectrally similar to vegeation in other rectangular plots.

UPDATE


I spent some time in eCognition exploring a newer algorithm " template matching". The technique is not new but it has been incorporated with the last release of eCognition. The concept is given a template, the template moves over the image (a single layer) in a sliding window and calculates normalized cross-correlation simalarity between the template and the pixels within the sliding window. The result is an cross-correlation image. Subsequently a threshold value is used to find position of pixels with higher cross-correlation value.

The concept of normalized cross-correlation is shown below taken from a good presentation. Study the presentation in detail if you want.Notice border effect of the cross-correlation image below. This can be avoided if padding with replicated pixels are added in the image (commonly done in MATLAB) for any convolution procedure.

The detail explanation for performing the template matching in eCognition will follow sometime in future.

Cross-correlation concept

A genarated template with many samples.

Cross-Correlation image

Result of template matching in eCognition



Tuesday, 28 October 2014

eCognition tutorial: Almost connected components for clumps identification in eCognition

This post is inspired from a post by Steve Eddins, who works in Math works, a company that build MATLAB. He is a software development manager in the MATLAB and one of the co-author of a book " Digitial image processing with MATLAB".I use both MATLAB and eCognition, so I ponder if this can be done in eCognition. eCognition has basic Morphological Operators like dilation and erosion . Advance MM operators like by opening by reconstruction, connected component labeling or skeleton and many others are not available in eCognition.

The problem of almost connected components:

There is simple synthetic image containing a number of circular blobs.  How can we label and measure the three clumps instead of the smaller circles? Two circles are almost connected if circles are within 25 pixels unit.

Binary circles
Connected components labeling
Almost connected components labeling

Of course it can be solved in eCognition. But for this, you have to  be familiar with many concepts in eCognition. Concepts such as PPO, object variables, multi-level representation and temporary layers are required. My workflow for  the solution is as follows:

  • Use multi-threshold segmentation to get circles
  • Use distance map algorithm to get binary distance map
  • Use chessboard segmentation to get pixel level unclassified objects
  • Use  multi-thresholding segmentation based on the distance map to get  clump
  • Copy level above
  • Use object variable concept to assign each clump a unique ID
  • Convert to sub-objects to get original circle at upper level

I will post rule-set after some time. I have given you enough hint how to proceed. Get your hands dirty !

Almost connected components labelling within eCognition
The concept of “almost connected components” can be applicable in remote sensing for clustering buildings detected in remote sensing images for analyzing of micro-climate of urban areas. There can be various other applications. Can you think of any ?

Monday, 27 October 2014

eCognition tutorial: Image object fusion in eCognition: Example of water bodies classification

eCognition is a powerful software for analysis for remote sensing images. Many people have this false impression that eCognition is all about segmentation. That’s not true. Segmentation is a just a part of it big chain that may involve segmentation, temporary classification, fusion, exploitation of contextual information etc. Many people believe that segmentation should be perfect at first time which is a fallacy. You can modify your segments as more information becomes available during the analysis. Typically in my any project I use segmentation at least 10 times. Yes at least 10 times .One of  the underutilized feature of eCognition is “Image Object Fusion” algorithm.The algorithm is an essential part of "iterative segmentation and classification" approach of GEOBIA. In this blog, I will show an example of image object fusion for classification of water bodies in a small remote sensing image. The step involves:
  1. Segmentation
  2. Initial classification of water
    1. Establishment of customized feature RationNIR 
      • RationNIR = (meanNIR/(meanR+meanB+meanG+meanNIR))*100
    2. Classify objects that satisfy property
      • RationNIR  less than 15 
      • Area greater than 10 pixels ( to avoid small shadows)
  3. Image object fusion using PPO ( Parent Process Object) to get whole water body
    1. Starting from water classified in step 2, check neighboring water objects and if difference between water object and neighboring objects is less than 5 in RatioNIR. Run in a loop.
    2. Process all water objects. 
Original image
Initial segmentation
Initial water classification
Final segmentation after image object fusion
Final water classification using image object fusion
Very powerful image object fusion algorithm

Step 3 is a one liner algorithm using "Image object Fusion".  Notice various parameters like Class filter, candidates classes, fitting function threshold, use absolute fitting value and weighted sum.To help you understand, I have made a "gif" to elaborate what is going on.

Blue: Initial water
Yellow: Active object
Red: Fused water after image object fusion



Here is the whole Rule set for water classification with image object fusion.

Friday, 11 July 2014

Data exchange between MATLAB and Python: Reading and writing .mat fileswith Python

I am a MATLAB guy. I love MATLAB. I started with Fortan during my first degree at my Bachelor level. I came across with MATLAB only in year 2010 as a part of my Msc studies. Since then I been using it continuously for various tasks. Just recently, I started  using Python and I LOVE IT. The biggest reason being that Python is open-source and there are lots of Python libraries that can be used. But there are times; I have to shuffle data between MATLAB and python, because for some tasks I prefer MATLAB as I am accustom to it. So if you are in the same boat, then here I show you simple way to transfer data between MATLAB and Python. One has to use scipy.io module in Scipy for that purpose. If you have some old data or got some data online that are saved as MATLAB’s .mat file format, you can simply import it as:

import numpy as np
import scipy.io as sio
mydata = sio.loadmat('mydata.mat')

Now your mydata contains a dictinary with keys corresponding to the varible names saved in the original mydata.mat Saving a python variable to .mat file is also straight forward

# write one variable
x = np.arange(1,10,1)
# file name of the file
fname ='export_from_python.mat'
sio.savemat(fname, {'x':x})

When you read export_from_python.mat, you will get 'x' varialbe into MATLAB. If you want to write more than two variable:

# write two variables
x = np.arange(1,10,1)
y = np.ones((5,5))
fname ='export_from_python_1.mat'
sio.savemat(fname, {'x':x, 'y':y})

I do lot of work with classification of remote sensing images using many different types of machine learning algorithms. Proprietary software like ENVI and ERDAS are not flexible enough for me, as these software donot allow an efficient way to tune hyper-parameters that are algorithm specific. I dont like training models with defualt parameters. I do my model traning and classification in python. Here is the typical workflow.
  1.  Import image and training data in python using GDAL
  2. Train machine learning model in python using Sci-kit Learn
  3. For accuracy assessment, i do it within python but for accuracy assessment visualization, i export  targets and outputs vectors from Python to MATLAB
  4. Use 'plotconfusion' function from Neural Network toolbox for a visualization of confusion matrix. Here is the confusion Matrix  information that i got from MATLAB. Its nice, isnt it ?

Picture1
Confusion matrix

Friday, 7 February 2014

Example of extracting grid nodes in MATLAB

For last few posts, I am writing about morphological image analysis with python with open source package scikit-image. In this post I want to show benefit of morphological image analysis with some real application. I been working with road extraction from satellite images for past few weeks and  one of the common task is to extract the grid corner nodes of the road network. So let’s assume the road grid has been already extracted and we want to extract intersection of grid network. Here I am showing three approaches for that based on synthetic data. Obviously with real data, the task is more complex and might require many slight modifications.

Here is the grid. You can generate such grid with checkerboard function in MATLAB with minor processing (edge detection and hole filling). Intersections of of grid lines have a property that it has 4 white pixels in 4-N neighborhood.  We can exploit this property to extract it. I am going to show to ways by which it can be done and in addition, another method based on extraction of corners will also be shown.

%make a checkerboard
I=checkerboard(20, 10,10)>0.5;
imshow(I)
% detect edge with canny
BW = edge(I,'canny');
figure, imshow(BW)
%make square structural element to fill holes with closing
SE = strel('square', 3);
BW1 = imclose(BW, SE);
figure, imshow(BW1)
% make a skeleton of the to lines 1 pixel thick
BW2 = bwmorph(BW1,'skel',Inf);
figure, imshow(BW2)


1

 26


In mathematics and, in particular, functional analysis, convolution is a mathematical operation on two functions f and g, producing a third function that is typically viewed as a modified version of one of the original function .In simple word, convolution of image is a process where you scan your image from left to right and top to bottom within local neighborhood defined by user, and do mathematical calculation within the local neighborhood. Here we are going to use it for simply sum the number of pixels which are which are white within 3x3 neighborhood. As shown by above figure, if the point is an intersection grid point then at that point sum should be 5. Any points with less than 5 white pixels are not intersection grid points.

% with block processing and inline function with convolution
tic;
kernel = [0 1 0; ... %# Convolution kernel
1 1 1; ...
0 1 0];
sumX = conv2(double(BW2),kernel,'same');
result=sumX;
% only consider pixels which are in grid image
result (BW2==0)= 0
result(sumX<5)=0;
[r,c] = find(result>0);
toc;
figure,imshow((BW2)), hold on, plot(r,c,'r*');title ('with Convolution')
hold off
3
Way Two: With Mathematical Morphology (MM)
If you are working in the field of Geo-information and you still saying what the heck this ‘MM’ then seriously you should be acquainted with this field of image processing. You can use MM for classification, edge detection, filtering, segmentation, building detection and many other things. Grab a cup of coffee and Google MM in remote sensing; there is tons of stuff to read.  There are courses in MM taught in different universities which are one semester long, so you got an idea how vast the subject is. If you want to seriously know MM, then there is no better book than ‘ Morphological Image Analysis’ by P Soillie. Here we use ‘Erosion’ method of MM.  Time: 0.011184 seconds.

% method two with morphological analysis
tic;
SE = strel ('disk', 1);
result2 = imerode(BW, SE);
[r,c] = find(result>0);
toc;
figure,imshow((BW2)), hold on, plot(r,c,'b*'), title ('With MM Erosion')
hold off
4
Way Two:  Mathematical Morphology (MM)
There are many corner detection techniques such as Moravec, Harris, SIFT etc. Here, I am going to use Harris corner detector for intersection grid points. Time: 0.094848 seconds.

% detect corner by harris corner detector
tic;
C = corner(BW2,500 );
timet2 = toc;
toc;
figure,imshow(BW2);
hold on
plot(C(:,1), C(:,2), 'g*'); title('with harris corner detector')
hold off
5
Way Two:  With Harris Corner Detector
So you have seen there are number of ways to solve a particular problem. All above methods detected intersection points successfully. Among three methods, convolution required longest time for processing and MM required shortest time. The gain in computation cost between MM and Corner detection is 9 folds.  I did all this in MATLAB but it can easily coded in python with scikit-image.

Friday, 13 September 2013

MATLAB linking figure for simultaneous zooming and panning

Sometime back I have written a Matlab GUI, which allows you select variables from your work space and plot them in linked figures so that when you pan and zoom, other figures zoom automatically. Lately I have received a lot of request to share that GUI with other but unfortunately I am unable to do so as I developed it for some research works and I am not allowed to distribute it. But, I am going to share you a function which does that linking.

To use that function, download it from here. There is a test.m for testing purpose as well.

%first image
Im1 = imread('cameraman.tif');
% show first figure
imshow(Im1)
% threshold image
Im2 = Im1>50;
%show second image in another figure
figure,
imshow(Im2);
% then call linkaxes_shailesh ()
% remember that matriz size must be same</code>

Put it in a safe place in a folder, set path in Matlab to that folder so that the function is available in every Matlab session ( file> set path). Open two or more figure you want to link in but bear in mind that the variables used in the figures must of same size i.e. it should have same number of rows and columns. After that, call that function by typing linkaxes_shailesh in your command line or you can even call it within one of your m file or function files by linkaxes_shailesh ()  and viola, your figures will be linked.  Its simple as that, don’t believe? Try out yourself. Someone said rightly ‘ Seeing is believing’. I hope you find it useful.

<iframe width="560" height="315" src="//www.youtube.com/embed/QhqnGdk2yQU?list=UUHQMpdmbYQPJxqsnKuz9DUw" frameborder="0" allowfullscreen></iframe>





Monday, 10 June 2013

Maximum reflectance in a spectra of Multispectral or Hyperspectral image in MATLAB

This is a very short post, something related to processing of remote sensing images. The image can be either multi-spectral or hyper-spectral images. One of my colleagues asked me this simple help in MATLAB  He was trying that in ENVI with band-math and IDL, with no avail.

I wanted to produce 2 images from my hyper-spectral image: 1) showing the maximum reflectance value across the bands and 2) the band number where the maximum came from.

First step is to read the image in MATLAB, of course :). That's no-brainer. For that you have to use multibandread function. I have a written post about it earlier. Search in the site. Now you have your image read in the MATLAB.

Here is the code, that i have written to perform what my friend asked.Hope this is useful for someone else.

%find the number of rows and columns
[rows,cols,bands]= size(imt1);
%reshape it 
imt1= reshape(imt1,[],4)';
%find max_value and band which has maximum value
[max_value,idx]= max(imt1,[],1);
%reconstruct the image
band_image= reshape(idx,rows,cols);
max_image= reshape(max_value,rows,cols);

Saturday, 31 December 2011

Opening multispectral or hyperspectral ENVI files in MATLAB


ENVI/IDL is one of the most used remote sensing software package which has a nice programming interface known as IDL. Though I have been using IDL for quite some time now, I still prefer MATLAB over IDL because MATLAB has extensive help documentation with lots of useful demonstration which I think is lacking in IDL.

There is a function in MATLAB which not many people are aware of, which is called Multibandread. Multibandread can be use for any type of binary files such as bsq, bil and bip. As long as you know how the data is organized in the binary file, its data type, rows columns and no. of bands in the file you can read the file in MATLAB with Multibandread.  Multibandread requires following informations.

X = multibandread(filename, size, precision, offset, interleave, byteorder)

With ENVI files, you can find all these information in the header file of that ENVI file. Using that information, you can pass this information by manually typing or you can write a custom function which will open the header file, fetch those information from the header file and pass it to Multibandread. I usally do it with latter approach.
Opening whole remote sensing images in MATLAB is a bit tricky. Consider you have a hyperspectral data with 116 bands and you try to read whole image at one go. MATLAB will run out of memory. The wise thing is to read the image in a block by block (MxN), performing required operation in the block and later combining all blocks. 

One cautionary note, I have seen people doing some silly mistakes such as reading an ENVI file with 10 bands in a variable (image) and using imshow (image) to visualize it. They spend countless hours wondering why the Multibandread is not being able read their ENVI files. But they forget that imshow function can display only three band one time. So if you want to view first three band then you have to use

  Imshow( image(:,:,1:3),[])

So, try Multibandread function if you are MATLAB savvy person and prefer MATLAB over IDL.
If you run into any kind of problem, I am ready for help.

Wednesday, 23 February 2011

MATLAB GUI for 3D point generation from SR 4000 images

Nowadays visualizations with a three dimensional impression are getting more and more interesting. This work of mine that I have carried out during my study concentrates on the construction of a 3D model of point clouds, by distance measurement with a time-of-flight (TOF) range camera, called SR 4000 which operates based on measurement of time of flight of Near infrared (NIR) beam. The task is to develop a tool for the collection of 3D point clouds achieving by this camera. The tool uses the collected 3D point coordinates from different scanning locations. This local coordinates from different camera positions according to the object should be transformed into a common coordinate system.

With the camera SR 4000 it is possible to capture point clouds with a maximum distance of 5 meters. Typical measuring accuracy is ± 1.5 m away from the structure. Pictures from different position around an object were taken in a day light sun. For resulting image coordinates, corrections have been applied for distortions such as radial distortions (symmetric distortion attributable to variation in refraction at each individual components lens) and tangential or decentring distortion (asymmetric distortion attributable to decentring and misalignment of individual lens elements within the objective).

Additionally a Matlab based GUI is implemented which processes and visualizes the MATLAB code of the tool on a graphical user interface. Graphical user interface was created such that it would guide any end user to go through all those process mentioned above without actually having deal with text based command interface. Also they don’t have to care about what input parameters has to supply for any functions. Users are guided through all the process with the help of graphical buttons and visual container and are aided with the help tip tools and message box.

[youtube http://www.youtube.com/watch?v=bipueUV01X8&w=700&h=400]

MATLAB GUI for 3D point generation from SR 4000 images

Nowadays visualizations with a three dimensional impression are getting more and more interesting. This work of mine that I have carried out during my study concentrates on the construction of a 3D model of point clouds, by distance measurement with a time-of-flight (TOF) range camera, called SR 4000 which operates based on measurement of time of flight of Near infrared (NIR) beam. The task is to develop a tool for the collection of 3D point clouds achieving by this camera. The tool uses the collected 3D point coordinates from different scanning locations. This local coordinates from different camera positions according to the object should be transformed into a common coordinate system.

With the camera SR 4000 it is possible to capture point clouds with a maximum distance of 5 meters. Typical measuring accuracy is ± 1.5 m away from the structure. Pictures from different position around an object were taken in a day light sun. For resulting image coordinates, corrections have been applied for distortions such as radial distortions (symmetric distortion attributable to variation in refraction at each individual components lens) and tangential or decentring distortion (asymmetric distortion attributable to decentring and misalignment of individual lens elements within the objective).

Additionally a Matlab based GUI is implemented which processes and visualizes the MATLAB code of the tool on a graphical user interface. Graphical user interface was created such that it would guide any end user to go through all those process mentioned above without actually having deal with text based command interface. Also they don’t have to care about what input parameters has to supply for any functions. Users are guided through all the process with the help of graphical buttons and visual container and are aided with the help tip tools and message box.

Friday, 17 December 2010

Visualization in Google Earth generated with KML using MATLAB

Well, I am bored again. That means time to write a new post :) . This time, I am going to utilized the knowledge that i have gained while writing my previous post KML creation with Matlab. I will show you Embassies of Nepal that are in different part of the world. I have used the same code that I have explained in the previous post and modified it so that i can display Embassy location as markers together with path connecting capital of Nepal and a particular Embassy location. The information about Nepalease Mission Abroad was taken from a page of Ministry of Foreign Affairs of Nepal. However, it doesn't contain latitude and longitude information that are required to draw point in Google Earth but instead it has only Address information. Therefore I downloaded the page information in MS Excel and formatted it as a list. Now, I have address information of each Embassy which needed to be Geocoded to get information about its latitude and longitude. Therefore, i wrote a PHP code which will send the addresses one at a time to Google and returns latitude and longitude information as a list. For those who are not familiar with PHP, similar task of converting address list to latitude and longitude list can be also achieved with this site.

Now my list in Excel looks like this.



Using that table and some coding in MATLAB, I created this beautiful visualization in Google Earth. Now that's cool. Isn't it? Flag of Nepal represents embassy of Nepal in that location and when a user clicks on it, information about it will be displayed in the pop up balloon. Double clicking on it, will zoom the Google Earth to that location.


I will write about the step wise explanation of MATLAB code to create such visualization next time when i will be bored again :). Now I am off for couple of beers after all its Friday evening! Ohh yeah!!

Visualization in Google Earth generated with KML using MATLAB

Well, I am bored again. That means time to write a new post :) . This time, I am going to utilized the knowledge that i have gained while writing my previous post KML creation with Matlab. I will show you Embassies of Nepal that are in different part of the world. I have used the same code that I have explained in the previous post and modified it so that i can display Embassy location as markers together with path connecting capital of Nepal and a particular Embassy location. The information about Nepalease Mission Abroad was taken from a page of Ministry of Foreign Affairs of Nepal. However, it doesn't contain latitude and longitude information that are required to draw point in Google Earth but instead it has only Address information. Therefore I downloaded the page information in MS Excel and formatted it as a list. Now, I have address information of each Embassy which needed to be Geocoded to get information about its latitude and longitude. Therefore, i wrote a PHP code which will send the addresses one at a time to Google and returns latitude and longitude information as a list. For those who are not familiar with PHP, similar task of converting address list to latitude and longitude list can be also achieved with this site.

Now my list in Excel looks like this.



Using that table and some coding in MATLAB, I created this beautiful visualization in Google Earth. Now that's cool. Isn't it? Flag of Nepal represents embassy of Nepal in that location and when a user clicks on it, information about it will be displayed in the pop up balloon. Double clicking on it, will zoom the Google Earth to that location.


I will write about the step wise explanation of MATLAB code to create such visualization next time when i will be bored again :). Now I am off for couple of beers after all its Friday evening! Ohh yeah!!

Friday, 10 December 2010

KML creation using MATLAB

In this post, I would like to show MATLAB capabilites for handling XML file. Specifically, I will show you how to create a DOM from scratch and then build up a simple XML document. The data I will use is a excel file with longitude and latitude information of number of points along the border of my country Nepal. Using the MATLAB capabilites for handling XML file, i will show how to generate KML out of it which can be readily visualize in Google Earth.

Here is a glimpse of Excel file to show how the data is stored in the Excel.


MATLAB provides a Java method com.mathworks.xml.XMLUtils.createDocument() to create a new node. In this example, we create the top level ("root" or "document") node to be named KML then populate it with child nodes with necessary information.

Step 1) Create a structure in MATLAB to store the data in the Excel file and populate the data in that structure. MATLAB provides a simple function xlsread by which xls files can be easily read.



Step 2) Create a top level node  and other necessary child level node. Since, we want to display multiple markers in KML, we need it store multiple points in a folder. In addition, I want to also show you how to display cutom markers in KML instead of using Google's default red markers. To create node, you will use .createElement ( ) and to insert node into a  super node, you will use .appendChild ( ). Value of a node is set using .setTextContent ( ) and attributes of a node is set using .setAttribute ( ). In the example, I have stored the image location of a flag of my country Nepal in the hrefNode  and set id attributes of the node StyleNode to nepal.



Step 3) Create multiple Placemarks node and store longitude and latitude information. For this, I am using a loop to create a placemarkNode as well as necessary other nodes and populating the cordinatesNode  with longitude and latitude information from the structure created beforehand using .setTextContent ( ).


Step 4) Store the thus created xml as KML file with xmlwrite function.


Step 5) View the file thus created in a Notepad ++. By the way, if you are still using convetional Notepad that comes with windows, give a shot to Notepadd++ which is much superior to Notepad and supports many programming language.




Step 5) Visualize the KML file. Download the KML file here.






KML creation using MATLAB

In this post, I would like to show MATLAB capabilites for handling XML file. Specifically, I will show you how to create a DOM from scratch and then build up a simple XML document. The data I will use is a excel file with longitude and latitude information of number of points along the border of my country Nepal. Using the MATLAB capabilites for handling XML file, i will show how to generate KML out of it which can be readily visualize in Google Earth.

Here is a glimpse of Excel file to show how the data is stored in the Excel.


MATLAB provides a Java method com.mathworks.xml.XMLUtils.createDocument() to create a new node. In this example, we create the top level ("root" or "document") node to be named KML then populate it with child nodes with necessary information.

Step 1) Create a structure in MATLAB to store the data in the Excel file and populate the data in that structure. MATLAB provides a simple function xlsread by which xls files can be easily read.



Step 2) Create a top level node  and other necessary child level node. Since, we want to display multiple markers in KML, we need it store multiple points in a folder. In addition, I want to also show you how to display cutom markers in KML instead of using Google's default red markers. To create node, you will use .createElement ( ) and to insert node into a  super node, you will use .appendChild ( ). Value of a node is set using .setTextContent ( ) and attributes of a node is set using .setAttribute ( ). In the example, I have stored the image location of a flag of my country Nepal in the hrefNode  and set id attributes of the node StyleNode to nepal.



Step 3) Create multiple Placemarks node and store longitude and latitude information. For this, I am using a loop to create a placemarkNode as well as necessary other nodes and populating the cordinatesNode  with longitude and latitude information from the structure created beforehand using .setTextContent ( ).


Step 4) Store the thus created xml as KML file with xmlwrite function.


Step 5) View the file thus created in a Notepad ++. By the way, if you are still using convetional Notepad that comes with windows, give a shot to Notepadd++ which is much superior to Notepad and supports many programming language.




Step 5) Visualize the KML file. Download the KML file here.