Crater detection - Report

70
PROJECT REPORT By: Ayush Upadhyay Dept. of Geology & Geophysics, Indian Institute of Technology, Kharagpur Supervised by: Dr. P. K. Champati Ray Scientist ‘SG’ Head, Geosciences Division Indian Institute of Remote Sensing, Dehradun Indian Institute of Remote Sensing Indian Space Research Organization 4, Kalidas Road, Dehradun - 248001 Crater Boundary Detection and Size Frequency Distribution (SFD) using MATLAB ® iirs

Transcript of Crater detection - Report

Page 1: Crater detection - Report

PROJECT REPORT

By:

Ayush Upadhyay Dept. of Geology & Geophysics,

Indian Institute of Technology, Kharagpur

Supervised by: Dr. P. K. Champati Ray

Scientist ‘SG’ Head, Geosciences Division

Indian Institute of Remote Sensing, Dehradun

Indian Institute of Remote Sensing Indian Space Research Organization

4, Kalidas Road, Dehradun - 248001

Crater Boundary Detection and Size Frequency Distribution (SFD) using MATLAB®

iirs

Page 2: Crater detection - Report

2 iirs

PROJECT REPORT

Submitted for the completion of Summer Training from 3rd May, 2011 to 30th June, 2011

By Ayush Upadhyay

2nd Year Student of Applied Geology, . Dept. of Geology & Geophysics,

Indian Institute of Technology, Kharagpur E-mail:

[email protected]

Supervised by Dr. P. K. Champati Ray

Head, Geosciences Division Scientist ‘SG’

Indian Institute of Remote Sensing, Dehradun Indian Space Research Organization 4, Kalidas Road, Dehradun - 248001

iirs

Crater Boundary Detection and Size Frequency Distribution (SFD) using MATLAB®

Page 3: Crater detection - Report

3 iirs

Certificate

This is to certify that ‘Mr. AYUSH UPADHYAY’ of Indian Institute of Technology, Kharagpur, has carried out the project titled as “CRATER BOUNDARY DETECTION AND SIZE FREQUENCY DISTRIBUTION (SFD) USING MATLAB®” under the guidance of Dr. P.K. Champati Ray, Head, Geosciences Division, IIRS, for the completion of Summer Training at Indian Institute of Remote Sensing, Indian Space Research Organization, Dept. of Space, Govt. of India, Dehradun during May-June, 2011.

Place: Dehradun Date:

Dr. P. K. Champati Ray Head, Geosciences Division

Project Guide

Page 4: Crater detection - Report

4 iirs

CONTENTS

• Acknowledgement • Abstract 1. Autonomous Crater Detection

• Hough Transformation • Theory • Circle Detection using Hough Transformation.

• Using the code (in MATLAB®) • Implementation

2. Circle Detection

• 3 Point Circle Detection Method • Algorithm • Calculations • Coding Implementation

• 4 Point Circle Detection Method • Algorithm • Calculations • Coding Implementation

• Arc Detection • Algorithm • Calculations • Coding Implementation

3. Ellipse Detection • Algorithm & Calculations • Coding Implementation

4. Software Usability • Operating the Software • Exporting data to ArcGIS® • Troubleshooting

• Reference • Annexure : The Code

Page 5: Crater detection - Report

5 iirs

Acknowledgement I take this opportunity to thank Indian Institute of Remote Sensing, Dehradun for giving me an opportunity to do Summer Training. I owe my gratitude to Dr. P.S. Roy, Director IIRS for giving me opportunity to pursue this training as well as for all necessary support and for all the facilities provided in IIRS. I am extremely grateful to Dr. P.K. Champati Ray, Head Geosciences Division and Project Supervisor for his valuable suggestions, guidance, scientific intellect and comments throughout the project. I would also like to thank Mr. Kedovikho Yhoshu and Mr. Ashish Dhiman for providing every possible help required during the course of my project. Special thanks to my friends Nitesh Jha and Gaurav Gupta, for motivating me from time to time. Last but not least, I would like to thank my Parents for supporting all my decisions, and providing me strength and motivation to complete this project.

Page 6: Crater detection - Report

6 iirs

Abstract Impact craters are formed when two celestial bodies collide with each other leading to formation of a depression on a planetary surface. As the most common topographical feature, craters provide important information on planet formation and Geology, statistical information of the size and number of craters help in determining the geological age of a planetary surface. Since the number of craters present in the celestial bodies is quite large, it is therefore not feasible to manually identify and analyze the craters. Hence, a robust technique needs to be developed which can identify and analyze the craters autonomously. The shapes of most of the craters found resemble a circle or an ellipse. Hough Transformation is a technique to autonomously identify circles and ellipses. Unfortunately, the method tends to fail unless more than half of the circle arc is visible. This method was applied on various Lunar images from the Clementine Spacecraft and MiniSAR probe aboard Chandrayaan-I for autonomous crater detection and it was found that this method was successful to some extent in Clementine images but the results were not appreciable in MiniSAR images. Therefore, for all practical identification purposes, a Graphical User Interface (GUI) was developed using MATLAB® comprising of various shape detection utilities which facilitate crater detection accurately and speedily. The interface provides a user with a ‘point and click’ interface to perform shape plotting operations on an image. Shape plotting operation include plotting a 3 Point Arc, 3 Point Circle, 4 Point Circle and 5 Point Ellipse. The interface provides option to Save the plotted Data, plot graphs from the Data and to Export data to other Softwares like ArcGIS® for further operations and analysis.

Page 7: Crater detection - Report

7 iirs

1. Autonomous Crater Detection The term Impact crater can be applied to any depression, natural or manmade, resulting from the high velocity impact of a projectile with a larger body. In most common usage, the term is used for the approximately circular depression in the surface of a planet, moon or other solid body in the System; Impact craters provide important information on planet formation and geology. Craters also inform selection of landing sites, as well as provide valuable data for path planning and rover navigation. In addition, craters help scientists align a variety of disparate data sets (radar, laser altimetry, etc.) to each other.

Impact craters are the dominant landforms on many solid Solar System objects including the Moon, Mercury, Callisto, Ganymede and most small moons and the asteroids. On other planets and moons that experience more-active surface geological processes, such as Earth, Venus, Mars, Europa, Io and Titan, visible impact craters are less common because they become eroded, buried or transformed by tectonics over time. Where such processes have destroyed most of the original crater topography, the terms impact structure or astrobleme are more commonly used. In early literature, before the significance of impact cratering was widely recognised, the terms cryptoexplosion or cryptovolcanic structure were often used to describe what are now recognized as impact-related features on Earth.

Detecting these features is of keen interest to mission planers and scientists at various space agencies. Large-scale, automatic and robust crater detection algorithms can help solve one of the most challenging and important data mining problems in space exploration.

Various methods for detecting Craters autonomously using Computer Vision have been applied but the methods have a high error percentage and the images from various satellites differ a lot from one another along with their thresholding conditions.

In most of the cases, impact craters are often in the shape resembling a circle or an ellipse. Here, in this report we would be discussing autonomous circle detection using various edge detection techniques.

Page 8: Crater detection - Report

8 iirs

Edge Detection Technique Used 1.1 Hough Transformation Hough edge detection technique is mainly used for detecting straight lines in an image; However, the algorithm can be modified to detect arbitrary shapes such as circles and ellipses for a given set of parameters. The purpose of the technique is to find imperfect instances of objects within a certain class of shapes by a voting procedure. This voting procedure is carried out in a parameter space, from which object candidates are obtained as local maxima in a so-called accumulator space that is explicitly constructed by the algorithm for computing the Hough transform. The Hough Transform is composed of two parts:

• Classical Hough Transform, which is applicable to lines and curves that are Defined by slope-intercept parameters.

• Generalized Hough Transform (modified by Duda and Hart, 1972) for images which Are defined by angle-radius parameters.

For our purpose, we would be using the Generalized Hough Transform. Theory Classical Hough Transform, deals with lines of the type 𝒚𝒚 = 𝒎𝒎𝒎𝒎 + 𝒃𝒃, an accumulator array is used to store the unknowns in the Hough Transform operation, Hence, accumulator array’s dimension equals the number of unknowns. For example, the linear Hough transform problem has two unknown parameters: m and b. The two dimensions of the accumulator array would correspond to quantized values for m and b. For each pixel and its neighborhood, the Hough transform algorithm determines if there is enough evidence of an edge at that pixel. If so, it will calculate the parameters of that line, and then look for the accumulator's bin that the parameters fall into, and increase the value of that bin. By finding the bins with the highest values, typically by looking for local maxima in the accumulator space, the most likely lines can be extracted, and their (approximate) geometric definitions read off. The Peaks are found by using a threshold value. The threshold value determines which lines are to be found and how many are to be detected. However, due to imperfection errors in the edge detection step, there are usually errors in the accumulator space.

Page 9: Crater detection - Report

9 iirs

Classical Hough Transform method has its drawbacks. If the line is horizontal, then “m” is 0, and if the line is vertical, then “m” is infinite. To encounter this, the generalized form of Hough Transformation is used. Generalized form of Hough Transformation deals with the parametric form of line. In parametric form, a line is represented as a function of (r, Ɵ).

Hence, the equation of the line becomes of the form:

𝒚𝒚 = �−𝐜𝐜𝐜𝐜𝐜𝐜(Ɵ)𝐜𝐜𝐬𝐬𝐬𝐬(Ɵ)� 𝐱𝐱 + �

𝐫𝐫𝐜𝐜𝐬𝐬𝐬𝐬(Ɵ)�

Which reduces to: 𝒓𝒓(Ɵ) = 𝐗𝐗𝐜𝐜𝐜𝐜𝐜𝐜𝐜𝐜(Ɵ) + 𝐘𝐘𝐜𝐜𝐜𝐜𝐬𝐬𝐬𝐬(Ɵ)

The parameter r represents the distance between the line and the origin, while θ is the angle of the vector from the origin to this closest point and𝛉𝛉 ∈ [𝟎𝟎,𝟐𝟐𝛑𝛑). The coordinates of the origin are (Xo,Yo). EXAMPLE: For the purposes of executing a Hough Transform, particularly a Generalized Hough Transform, it needs to convert Cartesian coordinates [x,y] into polar coordinates [ρ,θ], where ρ is the line connecting the polar coordinate to the origin where the x-axis intersects the y-axis, and where θ is the angle between the x axis and ρ.

[From Pratt, Digital Image Processing, Wiley & Sons]

Page 10: Crater detection - Report

10 iirs

In (c), the Cartesian representation is then used to generate a family of lines which intersect at the source point. This point has a family of lines emanating from a common point. When we plot the coordinates of any given point in polar space against each other, we get the curve depicted in (d).

[From Pratt, Digital Image Processing, Wiley & Sons] In (e), we have 3 points, A, B and C. When plotting the curves for the three points in polar coordinates, these 3 points will have three curves that intersect at (ρ0,θ0). The intersection at (ρ0,θ0) confirms A, B and C as valid points. Thus, a valid line will pass through A, B and C

[From Pratt, Digital Image Processing, Wiley & Sons] Circle Detection using Hough Transformation Since the number of unknowns in circle detection are 3 (Xo, Yo & r). Therefore, a 3-Dimensional accumulator is used for the Generalized Hough Transform. While detecting circles, its difficult to find the local maxima in Hough space due to the unknown number of peaks, and the possibility of false peaks. The GHT (Generalized Hough Transform) algorithm is preferable in situations where the surroundings change to an appreciable extent. It samples the region of interest only as many times required to locate the circles.

Page 11: Crater detection - Report

11 iirs

A brief general description is given in a flowchart below:

In the beginning, the image is scanned for a connected pixel. Once a connected edge pixel is determined, its location is used to segment a part of the image (region of interest). The edge pixels which are relatively connected to the connected edge pixel are then stored in a list. Two Pixels are chosen at random to determine the edge. Then the circle parameters are calculated using three points on the edge. The parameters of the circle are stored in the accumulator and then that circle is removed from the image. The algorithm subsequently scans the whole image for circles and the image is completely processed. Preprocessing In preprocessing, the edge detection is done. Edge detection is done by thresholding. A thresholding value (th) is set. This value can be set manually or by choosing the minimum value between the two maxima of a grey-level histogram.

2. Select Connected Pixels (X,Y)

3. Segment relative to (X,Y)

4 . Sample Two Pixels

5. Calculate Parameters

6. Accululate Parameters

1.Preprocessing

Page 12: Crater detection - Report

12 iirs

Thresholding is carried out by comparing the grey level value of a Pixel. If the grey level value of the pixel is less than the threshold, it is set to black (0) and if the value is greater, the value of the pixel is set to white (255). Edge Detection is made by differentiating all pixels in the thresholded image. Differentiating pixel values gives us the absolute value of the gradient.

∇𝒇𝒇 = �𝜕𝜕𝜕𝜕𝜕𝜕𝜕𝜕�

𝒊𝒊 + �𝜕𝜕𝜕𝜕𝜕𝜕𝜕𝜕�

𝒋𝒋

Where, f indicates the grey-level of a pixel. Select Connected Pixel (X,Y) A pixel is considered to be connected if it holds at least three edge pixels in a 3x3 Mask.

1 1 1 1 1 1 1 1 1

The connectivity is checked by imposing the 3x3 mask to each pixel of the image. Segment relative to (X,Y) A list is created containing all the pixels which are relatively connected to the connected pixel. Sample 2 Pixels The sampling is carried out as a random process and it is checked that the two pixels are different. Calculate Parameters 3 points on the edge of the circle are sufficient the circle parameters which are the coordinates of the center and the radius. The circle formed from these parameters is of the form:

(𝑿𝑿 − 𝑿𝑿𝑿𝑿)𝟐𝟐 + (𝒀𝒀 − 𝒀𝒀𝑿𝑿)𝟐𝟐 = 𝒓𝒓𝟐𝟐 A detailed discussion on finding the circle parameters with given 3 points is done in Section 2.1 of this report.

Page 13: Crater detection - Report

13 iirs

Accumulate Parameters The data is collected in the accumulator for further usage, in our case, plotting circles using the accumulated data. It is important that the accumulator is able to store all the calculated parameters so that information is not truncated. Once, the circle parameters are stored in the accumulator, the program goes to again selecting the connected pixel and the cycle continues, till the whole image is processed. The algorithm used here is a modified version of the Standard Hough Transform aimed at improving the efficiency. Unfortunately, the method tends to fail unless more than half of the circle arc is visible. Using the Code (in MATLAB®) First, The image which has to be processed needs to be read in MATLAB. Also, for this operation, it must be a grayscale image. Make sure CircularHough_grd.m is in the current MATLAB Directory. The code for doing it is as follows : % Reading the Image in Variable I I = imread(‘image.tif’); % Making the Image Grayscale I = rgb2gray(I);

Applying Hough Transformation: % Calling Hough Transform Function % I is the image on which processing is to be done, whereas [5 20] denotes % the radius range, and 20 is the Gradient Threshold [accum, circen, cirrad] = ... CircularHough_Grd(I, [5 20],... 20, 13, 1); % eliminating zero radius circles if any(cirrad <= 0) inds = find(cirrad>0); cirrad = cirrad(inds); circen = circen(inds,:); end % Plotting the circled from the accumulated Data imshow(I2); hold on; plot(circen(:,1), circen(:,2), 'r+'); for ii = 1 : size(circen, 1) rectangle('Position',[circen(ii,1) - cirrad(ii), circen(ii,2) - cirrad(ii), 2*cirrad(ii), 2*cirrad(ii)],... 'Curvature', [1,1], 'edgecolor', 'b', 'linewidth', 1.5); end hold off;

Page 14: Crater detection - Report

14 iirs

Implementation The Hough Transform algorithm was applied to the following image by the Clementine* Spacecraft.

On applying the Hough Transformation Algorithm, we get the following result: {Radius Range: [0.5 15], Gradient Threshold: 20}

Page 15: Crater detection - Report

15 iirs

In the Image processing done above, we can see that in the Medium sized crater range, the program is able to detect 90% of the craters successfully. Now, moving on more complex images, the following image is also by the Clementine Spacecraft, However this image contains minuscule craters (relative to the image size).

*Clementine (officially called the Deep Space Program Science Experiment (DSPSE)) was a joint space project between the Ballistic Missile Defense Organization (BMDO, previously the Strategic Defense Initiative Organization, or SDIO) and NASA. Launched on January 25, 1994, the objective of the mission was to test sensors and spacecraft components under extended exposure to the space environment and to make scientific observations of the Moon and the near-Earth asteroid 1620 Geographos. [Source: Wikipedia]

Page 16: Crater detection - Report

16 iirs

Applying the Hough Transformation Algorithm in the last image, we get the following result:

{Radius Range: [0.1 25], Gradient Threshold: 10}

Here, we applied the thresholding conditions as well as radius values mainly for detecting the smaller craters, since in some of the craters, the gradient is not as prominent as it should be, hence, they aren’t detected. Also, due to the nature of the code, smaller craters are found inside larger craters, leading to erroneous data.

Page 17: Crater detection - Report

17 iirs

If we apply different thresholding conditions in the same image, we get different result.

{Radius Range: [5 50], Gradient Threshold: 15}

This method starts to fail when radius range is increased. As we can see in the above image, at increased radius ranges, full circles are sometime detected inside bigger circles causing the result to be erroneous. This algorithm mainly depends on the gradient thresholding, and the radius range, at appropriate and preferably small radius ranges, it works to a greater extent.

Page 18: Crater detection - Report

18 iirs

Applying, this transformation in the following image from MiniSAR probe aboard Chandrayaan I,

We get,

Page 19: Crater detection - Report

19 iirs

This method critically fails in the MiniSAR images, due to the uneven gradient of the craters present in the images. Therefore, a much more robust way for crater detection has to be developed in order to get the problem solved. Till then, for all practical purposes, we would be using Manual Point and click interface developed using MATLAB.

**

Page 20: Crater detection - Report

20 iirs

2. Circle Detection Moon craters are often found in the shape resembling a circle. The Size Frequency Distribution (SFD) plots of the crater diameter help in determining the Geological age of a region. The program uses following two methods for detecting craters resembling a circle:

1. 3 Point Circle Detection Method 2. 4 Point Circle Detection Method

In both methods, user selects points along the periphery of a crater (in the likeliness of a circle), and the program plots a fitting circle* from the given points and also finds out the center. The algorithm used for plotting the circles is discussed in the following section. The coordinates of the center and the radius of each circle marked can be stored in a .mat file, and can be used later. 2.1 3 Point Circle Detection Method The 3 point circle detection method uses the coordinates of three points along the periphery of a circle to plot the fitting circle. The coordinates are inputted using the ginput()function of MATLAB. After selecting each point, it is marked with a (+) sign.

3 (+) signs selected for the 3 point circle.

Page 21: Crater detection - Report

21 iirs

The coordinates are now subjected to the algorithm discussed in the next subsection. The program plots the circle on which the 3 points (P1, P2 & P3) lie and also returns its center.

The plotted Circle and the center.

ALGORITHM We have three points (P1, P2, P3) which lie on a circle. Let’s assume the radius of the circle to be R and the coordinates of its center to be (X0, Y0). This has been shown diagrammatically below:

Page 22: Crater detection - Report

22 iirs

Now, we can find the center of the circle and its radius. Using the fact that “The Perpendicular bisector of any Chord of a circle passes through the center of the circle”. 3 points on the circle will give us two perpendicular bisectors. The common point of these two perpendicular bisectors will give us the center of the circle. This has been shown diagrammatically below.

CALCULATIONS Two lines can be formed through 2 pairs of the three points, the first passes through the first two points P1 and P2 (Line A). Another line (Line B) passes through the next two points P2 and P3. The coordinates of the points P1, P2 and P3 are (X1,Y1), (X2,Y2) and (X3,Y3) respectively. The equation of these two lines is:

Line A : Ya = Ma(X0 – X1) + Y1

Line B : Yb = Mb(X0 – X2) + Y2

where m is the slope of the line given by : Ma = �𝑌𝑌2−𝑌𝑌1

𝑋𝑋2−𝑋𝑋1�

Mb = �𝑌𝑌2−𝑌𝑌1𝑋𝑋2−𝑋𝑋1

The centre of the circle is the intersection of the two lines perpendicular to and passing through the midpoints of the lines P1P2 and P2 P3. The perpendicular of a line with slope m has slope -1/m, thus equations of the lines perpendicular to lines a and b and passing through the midpoints of P1P2 and P2P3 are:

Y’a = − 1

𝑀𝑀𝑀𝑀�𝑋𝑋𝑋𝑋 − 𝑋𝑋1+𝑋𝑋2

2� + 𝑌𝑌1+𝑌𝑌2

2

Page 23: Crater detection - Report

23 iirs

Y’b = − 1

𝑀𝑀𝑀𝑀�𝑌𝑌𝑋𝑋 − 𝑋𝑋2+𝑋𝑋3

2� + 𝑌𝑌2+𝑌𝑌3

2

These two lines intersect at the centre (X0, Y0), solving for X0 and Y0 gives :

X0 = 𝑀𝑀𝑀𝑀𝑀𝑀𝑀𝑀 (𝑌𝑌1−𝑌𝑌3)+𝑀𝑀𝑀𝑀(𝑋𝑋1+𝑋𝑋2)−𝑀𝑀𝑀𝑀(𝑋𝑋2+𝑋𝑋3)2(𝑀𝑀𝑀𝑀−𝑀𝑀𝑀𝑀)

Y0 = (𝑋𝑋3−𝑋𝑋1)−𝑀𝑀𝑀𝑀(𝑌𝑌1+𝑌𝑌2)+𝑀𝑀𝑀𝑀(𝑌𝑌2+𝑌𝑌3)

2(𝑀𝑀𝑀𝑀−𝑀𝑀𝑀𝑀)

The radius can be calculated as the distance between the center of the circle and any point on the circle.

R = �(Xo− X1)2 + (Yo− Y1)2 Hence, we have the radius and coordinates of the center of the circle. CODING IMPLEMENTATION

1. The coordinates are selected using MATLAB’s ginput() function and are stored into two column vectors.

2. The vectors are then subjected to the above mentioned algorithm. 3. The algorithm returns the value of X coordinate of the center, Y coordinate of the

center and the radius of the center in the variables rad_x(count), rad_y(count) and radius(count) respectively. Where, count is a global counter.

4. The coordinates of the center (rad_x(count) & rad_y(count)) are plotted using MATLAB’s plot() function.

5. For plotting the circle, MATLAB’s rectangle() function with the curvature set at (1,1) is used.

However, at most of the times, craters present in the figure do not resemble a circle to the extent that its center can be found out using three points. For a more accurate analysis, we use the 4 Point Circle Detection method.

Page 24: Crater detection - Report

24 iirs

2.2 4 Point Circle Detection Method The 4 point circle detection method uses the coordinates of four points along the periphery of a circle to plot the fitting circle similar to the 3 Point method. After selecting each point, it is marked with a (+) sign.

4 (+) signs selected for the 4 point circle.

The coordinates are then subjected to the algorithm discussed in the next subsection. The program plots the best fitting circle and also returns its center.

The plotted Circle and the center

Page 25: Crater detection - Report

25 iirs

ALGORITHM The 4 Point method uses three points at a time to get the center and the radius. On taking an average of these data, we get the features of a ‘Mean/Average Circle’. This gives us a more accurate representation of the data. This has been shown in the diagram below:

Therefore, we have a total of 4C3 (=4) combinations of points and hence we get 4 centers and radii as the output. The average value of each individual parameter gives us the parameter of the mean/average circle. This has been shown in the diagram below.

The four coloured circle depict the 4 possible circles that can be made out of the 4 points. The center thick

circle (black) is the mean circle.

Page 26: Crater detection - Report

26 iirs

As shown in the figure, the Mean/average circle formed contains data from all the four points. Hence, the 4 Point method gives us a more accurate representation of the center when the craters do not resemble circle to a great extent. CALCULATIONS Using 3 points at a time, the radius and the coordinates of the center are calculated in the same way as it is calculated in the 3 Point method. We would be extending this method by averaging the individual parameters (X, Y and R).

Xavg = X1 + X2 + X3 + X4 Yavg = Y1 + Y2 + Y3 + Y4 Ravg = R1 + R2 + R3 + R4

CODING IMPLEMENTATION

1. Same algorithm is followed till point 3 of the 3 Point Method. 2. The average values of X, Y and R are calculated and stored in rad_x(count),

rad_y(count) & radius(count). 3. The coordinates of the center (rad_x(count) & rad_y(count)) are plotted

using MATLAB’s plot() function. 4. For plotting the circle, MATLAB’s rectangle() function with the curvature set

at (1,1) is used.

A more efficient way, of detecting the crater boundaries, is by Ellipse Detection method. Most of the craters (which to not resemble a circle) are in the shape of an ellipse.

Page 27: Crater detection - Report

27 iirs

2.3 Arc Detection Sometimes, multi ring craters are also developed on the Moon’s crust due to super impacts of the meteors on the surface of the moon. The very largest impacts create concentric rings of fault scarps hundreds of kilometers in diameter.

Mare Orientale on the Moon is the archetypical multiple-ring impact basin. Perhaps a billion years after the impact, lava flooded the low-lying parts of the basin and also pounded against some of the scarps

[Image Source: http://www.uwgb.edu/dutchs/planets/planfoto/moon/mareor4.jpg]

The program has an arc detection feature for this type of images. It uses 3 points to plot a crater between the starting (first) point and the ending (last) point.

The plotted Crater arcs and their centers.

Page 28: Crater detection - Report

28 iirs

ALGORITHM We have three points (P1,P2 and P3). The center and the radius of the arc is found out by the 3 Point circle method.

Now, since MATLAB doesn’t have a circle or an arc function inbuilt. Therefore we find the angle made by the first point (P1) and the last point (P3) with the horizontal in radians.

The angle is calculated and then using MATLAB’s plot() function, the arc is drawn.

Page 29: Crater detection - Report

29 iirs

CALCULATIONS

For the points P1(X1,Y1), P2(X2,Y2) and P3(X3,Y3), The angles Ɵ1 and Ɵ2 are calculated using following formulas.

Ɵ𝟏𝟏 = 𝐭𝐭𝐭𝐭𝐬𝐬−𝟏𝟏 �𝐘𝐘𝟏𝟏 − 𝐘𝐘𝐜𝐜

|𝐗𝐗𝟏𝟏 − 𝐗𝐗𝐜𝐜|�

Ɵ𝟐𝟐 = 𝐭𝐭𝐭𝐭𝐬𝐬−𝟏𝟏 �𝐘𝐘𝟐𝟐 − 𝐘𝐘𝐜𝐜

|𝐗𝐗𝟐𝟐 − 𝐗𝐗𝐜𝐜|�

Where, (Xo,Yo) are the coordinates of the center of the circle. CODING IMPLEMENTATION

• Same algorithm is followed till point 3 of the 3 Point Method. • A function can ang() is called which uses MATLAB’s linspace() function to

plot the plots between the start point (P1) and end point (P3). • The Angle datas are stored in angle_1 (Ɵ1) and angle_2 (Ɵ2).

**

Page 30: Crater detection - Report

30 iirs

3. Ellipse Detection Many a times, the impact craters found on the celestial bodies found on the celestial bodies are in the shape of an ellipse. This helps in determining the edge of a crater in a more efficient way, and the center of the ellipse is geometrically more correct than the 4 Point Circle. Ellipse detection is done by inputting 5 points from the image (by user) along the periphery of a crater (in the likeness of an ellipse).

5 (+) points selected for the Ellipse.

The five points are used to calculate the coordinates of the center, the Major and the Minor axis and the rotation (tilt) of the ellipse. The program plots the center, the ellipse and the major and minor axes as well.

The green lines represent the major and the minor axes. The (+) sign is the center of the ellipse.

Page 31: Crater detection - Report

31 iirs

ALGORITHM & CALCULATIONS We have 5 points from which we would draw a best fit ellipse.

The green lines represent the Major and Minor axes.

The following parameters should be determined in order to plot the ellipse from the given data. a : Sub axis (radius) of the X axis of the non-tilt ellipse b : Sub axis (radius) of the Y axis of the non-tilt ellipse ø : Orientation in radians of the ellipse (tilt) X0 : Center at the X axis of the non-tilt ellipse Y0 : Center at the Y axis of the non-tilt ellipse X0(tilt) : Center at the X axis of the tilted ellipse Y0(tilt) : Center at the Y axis of the tilted ellipse Major Axis : Size of the long axis of the ellipse Minor Axis : Size of the short axis of the ellipse Status : Status of detection of an ellipse

General (Conic) equation of an ellipse is given by :

𝒂𝒂𝒎𝒎𝟐𝟐 + 𝒃𝒃𝒎𝒎𝒚𝒚 + 𝒄𝒄𝒚𝒚𝟐𝟐 + 𝒅𝒅𝒎𝒎 + 𝒆𝒆𝒚𝒚 + 𝒇𝒇 = 𝟎𝟎 Where a,b,c,d,e and f are constants.

Page 32: Crater detection - Report

32 iirs

Now, we check if the ellipse if tilted or not. If the co-efficient of the xy term in an ellipse is non zero then the ellipse is tilted. In other words, if the term b is non zero, the ellipse is tilted, The equation of a Non tilted ellipse is given by :

𝒂𝒂𝒎𝒎𝟐𝟐 + 𝒄𝒄𝒚𝒚𝟐𝟐 + 𝒅𝒅𝒎𝒎 + 𝒆𝒆𝒚𝒚 + 𝒇𝒇 = 𝟎𝟎 To get the tilt value for the ellipse, we replace x with (cos(ø)x + sin(ø)y) and y with (-sin(ø)x + cos(ø)y). On simplifying, we get : 𝒎𝒎𝟐𝟐(𝒂𝒂𝐜𝐜𝐜𝐜𝐜𝐜(ø)𝟐𝟐 − 𝐛𝐛𝐜𝐜𝐜𝐜𝐜𝐜(ø)𝐜𝐜𝐬𝐬𝐬𝐬(ø) + 𝐜𝐜𝐜𝐜𝐬𝐬𝐬𝐬(ø)𝟐𝟐) + 𝐱𝐱𝐱𝐱 �𝟐𝟐𝐭𝐭𝐜𝐜𝐜𝐜𝐜𝐜(ø)𝐜𝐜𝐬𝐬𝐬𝐬(ø) + (𝐜𝐜𝐜𝐜𝐜𝐜(ø)𝟐𝟐 −

𝐜𝐜𝐬𝐬𝐬𝐬(ø)𝟐𝟐)𝐛𝐛 − 𝟐𝟐𝐜𝐜𝐜𝐜𝐬𝐬𝐬𝐬(ø)𝐜𝐜𝐜𝐜𝐜𝐜(ø)� + 𝐱𝐱𝟐𝟐(𝐭𝐭𝐜𝐜𝐬𝐬𝐬𝐬(ø)𝟐𝟐 + 𝐛𝐛𝐜𝐜𝐜𝐜𝐜𝐜(ø)𝐜𝐜𝐬𝐬𝐬𝐬(ø) + 𝐜𝐜𝐜𝐜𝐜𝐜𝐜𝐜(ø)𝟐𝟐) + 𝐱𝐱�𝐝𝐝𝐜𝐜𝐜𝐜𝐜𝐜(ø) − 𝐞𝐞𝐜𝐜𝐬𝐬𝐬𝐬(ø)� + 𝐱𝐱(𝐝𝐝𝐜𝐜𝐬𝐬𝐬𝐬(ø) + 𝐞𝐞�𝐜𝐜𝐜𝐜𝐜𝐜(ø)� + 𝐟𝐟 = 𝟎𝟎

Now, we can find the tilt by substituting the new value of coefficient of xy=0. On simplifying we get :

𝟐𝟐𝐭𝐭𝐜𝐜𝐜𝐜𝐜𝐜(ø) 𝒔𝒔𝒊𝒊𝒔𝒔(ø) + (𝐜𝐜𝐜𝐜𝐜𝐜(ø)𝟐𝟐 − 𝐜𝐜𝐬𝐬𝐬𝐬(ø)𝟐𝟐)𝐛𝐛 − 𝟐𝟐𝐜𝐜𝐜𝐜𝐬𝐬𝐬𝐬(ø)𝐜𝐜𝐜𝐜𝐜𝐜(ø) = 𝟎𝟎

Hence,

ø =𝟏𝟏𝟐𝟐𝐭𝐭𝐭𝐭𝐭𝐭𝐬𝐬(

𝐛𝐛𝐜𝐜 − 𝐭𝐭

)

ø =𝟏𝟏𝟐𝟐𝐭𝐭𝐭𝐭𝐬𝐬−𝟏𝟏 �

𝐛𝐛𝐜𝐜 − 𝐭𝐭�

Now, the the values of cos(ø) & sin(ø)can be calculated, from that all the values of constants (a’,b’,c’,d’ and e’) can be calculated for the substituted equation. The values of a’,b’,c’,d’ and e’ are :

𝒂𝒂′ = 𝒂𝒂𝒄𝒄𝑿𝑿𝒔𝒔(∅)𝟐𝟐 − 𝐛𝐛𝐜𝐜𝐜𝐜𝐜𝐜(∅)𝐜𝐜𝐬𝐬𝐬𝐬(∅) + 𝐜𝐜𝐜𝐜𝐬𝐬𝐬𝐬(∅)𝟐𝟐

𝒃𝒃′ = 𝟐𝟐𝒂𝒂𝒄𝒄𝑿𝑿𝒔𝒔(∅) 𝐜𝐜𝐬𝐬𝐬𝐬(∅) + (𝐜𝐜𝐜𝐜𝐜𝐜(∅)𝟐𝟐 − 𝐜𝐜𝐬𝐬𝐬𝐬(∅)𝟐𝟐)𝐛𝐛 − 𝟐𝟐𝐜𝐜𝐜𝐜𝐬𝐬𝐬𝐬(∅)𝐜𝐜𝐜𝐜𝐜𝐜(∅)

𝒄𝒄′ = 𝒂𝒂𝒔𝒔𝒊𝒊𝒔𝒔(∅)𝟐𝟐 + 𝐛𝐛𝐜𝐜𝐜𝐜𝐜𝐜(∅) 𝐜𝐜𝐬𝐬𝐬𝐬(∅) + 𝐜𝐜𝐜𝐜𝐜𝐜𝐜𝐜(∅)𝟐𝟐

𝒅𝒅′ = 𝒅𝒅𝒄𝒄𝑿𝑿𝒔𝒔(∅) − 𝐞𝐞𝐜𝐜𝐬𝐬𝐬𝐬(∅)

Page 33: Crater detection - Report

33 iirs

𝒆𝒆′ = 𝒅𝒅𝒔𝒔𝒊𝒊𝒔𝒔(∅) + 𝐞𝐞𝐜𝐜𝐜𝐜𝐜𝐜(∅)

We want the representation of non-tilted ellipse to be as:

�𝑿𝑿 − 𝑿𝑿𝑿𝑿

𝒂𝒂 �𝟐𝟐

+ �𝒀𝒀 − 𝒀𝒀𝑿𝑿𝒃𝒃 �

𝟐𝟐

= 𝟏𝟏

Where, (Xo,Yo) is the center of the ellipse, and a,b are the ellipse "radiuses" (or sub-axis).

So as to get the equation in the desired format, we would use Square completion methods(making perfect squares) to solve an equation. We define:

𝒇𝒇′′ = 𝒇𝒇′ + �𝒅𝒅′𝟐𝟐

𝟒𝟒𝒂𝒂′� + �

𝒆𝒆′𝟐𝟐

𝟒𝟒𝒄𝒄′�

Such that,

𝒂𝒂′(𝑿𝑿 − 𝑿𝑿𝑿𝑿)𝟐𝟐 = 𝒂𝒂′ �𝑿𝑿𝟐𝟐 + 𝑿𝑿𝒅𝒅′

𝒂𝒂′+ �

𝒅𝒅′

𝟐𝟐𝒂𝒂′�𝟐𝟐

𝒄𝒄(𝒀𝒀 − 𝒀𝒀𝑿𝑿)𝟐𝟐 = 𝒄𝒄′ �𝒀𝒀𝟐𝟐 + 𝒀𝒀𝒆𝒆′

𝒄𝒄′+ �

𝒆𝒆𝟐𝟐𝒄𝒄′

�𝟐𝟐�

Which on transformation, leads to:

𝑿𝑿𝑿𝑿 = −𝒅𝒅′

𝟐𝟐𝒂𝒂′

𝒀𝒀𝑿𝑿 = −𝒆𝒆′

𝟐𝟐𝒄𝒄′

𝒂𝒂 = ��𝒇𝒇′′

𝒂𝒂′�

𝒃𝒃 = ��𝒇𝒇′′

𝒄𝒄′�

Page 34: Crater detection - Report

34 iirs

The remaining parameters Major Axis and Minor Axis can be determined by:

𝑴𝑴𝒂𝒂𝒋𝒋𝑿𝑿𝒓𝒓 𝑨𝑨𝒎𝒎𝒊𝒊𝒔𝒔 = 𝟐𝟐𝐦𝐦𝐭𝐭𝐱𝐱(𝒂𝒂,𝒃𝒃)

𝑴𝑴𝒊𝒊𝒔𝒔𝑿𝑿𝒓𝒓 𝑨𝑨𝒎𝒎𝒊𝒊𝒔𝒔 = 𝟐𝟐 𝐦𝐦𝐬𝐬𝐬𝐬(𝒂𝒂,𝒃𝒃)

Hence, we have all the necessary parameters to plot the ellipse. NOTE: This method would not return any data if the points form a Conic which is either a hyperbola or parabola. CODING IMPLEMENTATION

1. The coordinates are selected using MATLAB’s ginput() function and are stored into two column vectors.

2. The vectors are then subjected to the above mentioned algorithm. 3. The code has been provided to make the best fit ellipse if more than 5 points are

given. A cost function is defined in the code which takes care of it. 4. The program returns the value of:

a,b,phi,X0,Y0,X0_in,Y0_in,major_axis,minor_axis & status. 5. The value of all the constants are calculated and are put in the general equation

of ellipse. MATLAB generated 100 points from the equation are plotted using the plot() function.

6. The lines and the center are also plotted using the MATLAB plot() function.

**

Page 35: Crater detection - Report

35 iirs

4. Software Usability This section explains all the features of the software in detail, along with a step by step procedure for using it. Operating the Software Starting from MATLAB

1. Start MATLAB. 2. Navigate to the Program directory. (generally named ‘crater’.) 3. Type ‘crater’ in the Command Window and press enter(↵).

Starting from standalone Crater_detection.exe

1. Open the program directory. 2. Navigate to the ‘src’ folder. 3. Run ‘Crater_detection.exe’.

NOTE: Executables and libraries created with the MATALAB compiler product use a runtime engine called the MATLAB Compiler Runtime (MCR). The MCR is provided with MATLAB compiler for distribution and can be deployed royalty-free. The location of the MATLAB Compiler Runtime in 64 Bit systems can be found in: X:\Program Files\MATLAB\<MATLAB_version>\toolbox\compiler\deploy\win64\MCRInstaller.exe In 32 Bit systems, the location is: X:\Program Files\MATLAB\<MATLAB_version>\toolbox\compiler\deploy\win32\MCRInstaller.exe Where, X is the Windows root directory.

Made using MATLAB®

Page 36: Crater detection - Report

36 iirs

The Interface

• Zooming and Panning tools : Lets you zoom and pan around the image. • File Management tools : Contains options for opening, closing and saving data. • Plotting Tools : Contains the options for drawing various plots • Data Exporting Tools : Contains options for exporting the data into softwares

like ArcGIS. • Graph Plotting Tools : Gives the option to plot SFD curves and reverting back to

the image. • Information Window : Shows the number of craters detected, X-Y coordinate

and radius of last drawn figure. • Image Pane : Contains the main image and the overlaying plots.

Opening an Image

1. Start the software. 2. Click on ‘Load Image’. 3. Browse to the image location and select the image. 4. Click ‘Open’.

Page 37: Crater detection - Report

37 iirs

Plotting Arcs/Circles/Ellipses 1. Open an Image. 2. Click on ‘3 point Arc’ to plot an arc using 3 points.

Click on ‘3 point Circle’ to plot a circle using 3 points. Click on ‘4 point Circle’ to plot an arc using 4 points. Click on ‘5 point Ellipse’ to plot an ellipse using 5 points.

3. Select 3 points in the figure, and your arc will be generated. 4. Any further plotting can be done by simply selecting the corresponding button.

Clear last Crater In case that any Crater object has been drawn incorrectly, it can be removed.

1. Click on ‘Clear Last Crater’ to clear the last drawn Crater object. WARNING : This feature works well with the removal of the ultimate (last immediate) crater. Removing penultimate crater and so forth can result in Data losses. Saving Data associated with an image

1. Plot all the arcs/circles/ellipses in an image. 2. Click on ‘Save Data’. 3. Specify the path and file name. 4. Your data is saved in a .mat file, and this can be used later.

Variables stored in the .mat file using ‘Save Data’ saves the following variables.

• COUNT = Total number of objects (arcs/circles/ellipses) plotted. • PARAMETER = A counter identifier. The value of PARAMETER varies for different

objects. Its 9 for an ellipse, 5 for a 4 Point Circle and 4 for a 3 Point circle. • angle_1 = The first angle of the arc. • angle_2 = The second angle of the arc. • horzi_line = The start and end point coordinates of the major axis of an

ellipse. • vert_line = The start and end point coordinates of the minor axis of an

ellipse. • major_axis = Length of the major axis of an ellipse. • minor_axis = Length of the minor axis of an ellipse. • rad_x = The X coordinate of the center of an object. • rad_y = The Y coordinate of the center of an object. • radius = The length of the radius of an object. • rot_ellipse = The points lying on the ellipse. (100 points)

Page 38: Crater detection - Report

38 iirs

Plotting from Saved Data The program us to plot the saved data on an Image. Steps for doing so :

1. Open the Image with which a relevant data is associated. 2. Use the ‘Plot from Saved Data’ function and select the data file pertaining to

that image. 3. The program plots the Data from the file.

Plotting Graphs The program is used to plot the Size Frequency diagrams.

1. Open an image and generate all the relevant plots. 2. Click on ‘Plot Graph’ to plot the graph. 3. The graph can be saved by clicking on the ‘Save Image’ in the file management

tools. 4. To Revert back to the image, click on the ‘Revert to Image’ button.

Formula used for age estimation using SFD.

Where, ao gives the geological age of the craters.

[Source : http://www.lpi.usra.edu/books/AsteroidsIII/pdf/3025.pdf]

Zooming and Panning The zooming and Panning tools are located in the Top-left corner of the screen.

Page 39: Crater detection - Report

39 iirs

Closing the Program

To close the program click on the button in the File Management tools. WARNING : Save all relevant Data before closing the program. 4.1 Exporting Data to ArcGIS® Data generated in the program (ellipse object) can be exported to the ArcGIS® as a shape file, and can be further used for various other applications. The program generates X-Y coordinates of the ellipse object in a Text File with ASCII encoding. The X-y coordinate data is then imported into an intermediate software – Global Mapper. Global mapper joins the X-Y data to form shapes, which then can be exported as a .dxf* file. The .dxf file is then imported in ArcGIS as a Polygon Shape file. The step by step procedure for exporting the Data is described in the next section. Steps for Exporting Data

1. Opening an Image and Plotting relevant Data a. Open the Image. b. Generate plots in it.

* .dxf Extension : AutoCAD DXF (Drawing Interchange Format, or Drawing Exchange Format) is a CAD data file format developed by Autodesk f enabling data interoperability between AutoCAD and other programs.

Page 40: Crater detection - Report

40 iirs

2. Exporting the Data as a Text File a. For MiniSAR images the value of Spatial Resolution to be put is 75. Since,

each pixel value corresponds to the value 75m. b. Click on ‘Export Data’. c. Specify the Filename and Pathname.

3. Importing Data in Global-Mapper

a. Open Global-Mapper. b. Go to File > Open Generic ASCII Text File(s)

c. Select the file. d. A dialog box will open up, Click ‘OK’ to proceed.

Page 41: Crater detection - Report

41 iirs

e. Click ‘OK’ again to proceed. f. Click ‘OK’again to proceed. g. You will see the shapes of the ellipses on the screen.

h. Click on File > Export Vector Data > Export DXF

i. Click on OK and then again OK. j. Save the File.

Page 42: Crater detection - Report

42 iirs

k. Open a new map in ArcGIS® and open the same image on which the data had been plotted as a layer using ‘Add Data’. WARNING : The Image must be georeferenced.

l. Now open the .dxf using ‘Add Data’, browse to the file and select ‘Polygon’.

Page 43: Crater detection - Report

43 iirs

m. The shapes get plotted over the figure.

n. On changing the symbology we get.

Page 44: Crater detection - Report

44 iirs

The shapes are successfully imported. A comparison of the plots is given.

Page 45: Crater detection - Report

45 iirs

Troubleshooting - Known Issues

• The number of crater detected is incorrect. Plz. Close the program and restart.

Reference

• Hough Transformation Digital Image Processing – William K Pratt [Wiley]

• Circle Detection using Hough Transformation http://linux.fjfi.cvut.cz/~pinus/bristol/imageproc/hw1/report.pdf http://www.cvmt.dk/~tbm/Publications/hough.pdf

• Ellipse Reference: http://mathworld.wolfram.com/Ellipse.html

• Multi Ring Craters: http://www.uwgb.edu/dutchs/planets/cratform.htm

• Size Distribution Curve http://www.lpi.usra.edu/books/AsteroidsIII/pdf/3025.pdf

• MATLAB Compiler documentation:

http://www.mathworks.com/products/compiler/

Page 46: Crater detection - Report

46 iirs

Annexure

The Code

Main Function File (Crater.m) function varargout = Crater(varargin) % CRATER M-file for Crater.fig % CRATER, by itself, creates a new CRATER or raises the existing % singleton*. % % H = CRATER returns the handle to a new CRATER or the handle to % the existing singleton*. % % CRATER('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in CRATER.M with the given input arguments. % % CRATER('Property','Value',...) creates a new CRATER or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before Crater_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to Crater_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help Crater % Last Modified by GUIDE v2.5 16-Jun-2011 12:46:11 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @Crater_OpeningFcn, ... 'gui_OutputFcn', @Crater_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % undo(n=1) removes the last n figure items added

Page 47: Crater detection - Report

47 iirs

function undo(n) %Checking number of Variables Used if nargin==0 n=1; end if ischar(n) n = sscanf(n,'%i'); end % Removinf last operations from axis. if n<1 error(['Not undoing ' int2str(n) ' items']); end g=get(gca,'children'); L=length(g); for i=1:n delete(g(i)); end % --- Executes just before Crater is made visible. function Crater_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to Crater (see VARARGIN) % Choose default command line output for Crater handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes Crater wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = Crater_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in file_open. function file_open_Callback(hObject, eventdata, handles) % hObject handle to file_open (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Pathname global Filename global y_data [Filename, Pathname] = uigetfile('*.*', 'Pick an image'); % Data input; fetches for the image file. I = fullfile(Pathname, Filename); % Appends the file path and the file name together. img = imread(I); %getting pixel Data [pixel_data] = size(img);

Page 48: Crater detection - Report

48 iirs

y_data = pixel_data(1); %Displaying Pixel data set(handles.y_cord,'String',y_data); % Reads the image and store it to a variable. imshow(img); % Displays the image. handles.picture = img; % Creates the handle for the image for modifications. guidata(hObject, handles); % Update handles structure. % -------------------------------------------------------------------- function Untitled_1_Callback(hObject, eventdata, handles) % hObject handle to Untitled_1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in exit_button. function exit_button_Callback(hObject, eventdata, handles) % hObject handle to exit_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %Initialize variables global COUNT global rad_x global rad_y global PARAMETER global radius global major_axis global minor_axis %Setting Variables to Zero COUNT = 0; radius = []; rad_x = []; rad_y = []; PARAMETER = []; major_axis=[]; minor_axis=[]; close % -------------------------------------------------------------------- function get_pixel_ClickedCallback(hObject, eventdata, handles) % hObject handle to get_pixel (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function uitoggletool6_ClickedCallback(hObject, eventdata, handles) % hObject handle to uitoggletool6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)

Page 49: Crater detection - Report

49 iirs

% --- Executes on button press in select_point_three. function select_point_three_Callback(hObject, eventdata, handles) % hObject handle to select_point_three (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %Initializing Variables global COUNT global radius global rad_x global rad_y global PARAMETER global major_axis global minor_axis global angle_1 global angle_2 if isempty(COUNT) COUNT = 0; end %Inputting Coordinates for i=1:3, [x y] = ginput(1); a(i) = x; b(i) = y; hold on; plot(x,y,'r+'); set(handles.x_cord,'String',a(i)); set(handles.y_cord,'String',b(i)); %number of Circles Drawn end %Incrementing Count COUNT = COUNT + 1; %printing number of Circles set(handles.circ_num,'String',COUNT); %calculating circle radii and center %slope of the lines m_1 = (b(2)-b(1))/(a(2)-a(1)); m_2 = (b(3)-b(2))/(a(3)-a(2)); %calculation of the center points rad_x(COUNT) = ((m_1)*(m_2)*(b(1)-b(3))+((m_2)*(a(1)+a(2)))-(m_1)*(a(2)+a(3)))/(2*(m_2-m_1)); rad_y(COUNT) = ((a(3)-a(1))-(b(1)+b(2))*(m_1)+(b(2)+b(3))*(m_2))/(2*(m_2-m_1)); %calculation of the radius radius(COUNT) = ((rad_x(COUNT)-a(1))^2+(rad_y(COUNT)-b(1))^2)^0.5; %Setting Other Parameters Zero major_axis(COUNT)=0; minor_axis(COUNT)=0; angle_1(COUNT)=0; angle_2(COUNT)=0; set(handles.cord,'String',radius(COUNT)); %plotting the circle

Page 50: Crater detection - Report

50 iirs

h(COUNT) = plot(rad_x(COUNT),rad_y(COUNT),'b+'); rectangle('Position',[rad_x(COUNT) - radius(COUNT), rad_y(COUNT) - radius(COUNT), 2*radius(COUNT), 2*radius(COUNT)],... 'Curvature', [1,1], 'edgecolor', 'r', 'linewidth', 1.5); PARAMETER(COUNT) = 5; guidata(hObject, handles); % --- Executes on button press in clear_image. function clear_image_Callback(hObject, eventdata, handles) % hObject handle to clear_image (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) cla; %clears The Image Axes guidata(hObject,handles); % --- Executes on button press in select_point_four. function select_point_four_Callback(hObject, eventdata, handles) % hObject handle to select_point_four (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %Initialize Variables global COUNT global radius global rad_x global rad_y global PARAMETER global major_axis global minor_axis global angle_1 global angle_2 if isempty(COUNT) COUNT = 0; end %Inout 4 points for i=1:4, [x y] = ginput(1); a(i) = x; b(i) = y; hold on; plot(x,y,'r+'); set(handles.x_cord,'String',a(i)); set(handles.y_cord,'String',b(i)); %number of Circles Drawn end %Incrementing Count COUNT = COUNT + 1; %printing number of Circles set(handles.circ_num,'String',COUNT); %calculating circle radii and center %slope of the lines m_1_one = (b(2)-b(1))/(a(2)-a(1)); m_2_one = (b(3)-b(2))/(a(3)-a(2));

Page 51: Crater detection - Report

51 iirs

m_1_two = (b(4)-b(1))/(a(4)-a(1)); m_2_two = (b(3)-b(4))/(a(3)-a(4)); %calculation of the center points rad_x_one = ((m_1_one)*(m_2_one)*(b(1)-b(3))+((m_2_one)*(a(1)+a(2)))-(m_1_one)*(a(2)+a(3)))/(2*(m_2_one-m_1_one)); rad_y_one = ((a(3)-a(1))-(b(1)+b(2))*(m_1_one)+(b(2)+b(3))*(m_2_one))/(2*(m_2_one-m_1_one)); rad_x_two = ((m_1_two)*(m_2_two)*(b(1)-b(3))+((m_2_two)*(a(1)+a(4)))-(m_1_two)*(a(4)+a(3)))/(2*(m_2_two-m_1_two)); rad_y_two = ((a(3)-a(1))-(b(1)+b(4))*(m_1_two)+(b(4)+b(3))*(m_2_two))/(2*(m_2_two-m_1_two)); rad_x(COUNT) = (rad_x_one + rad_x_two)/2; rad_y(COUNT) = (rad_y_one + rad_y_two)/2; %calculation of the radius radius_one = ((rad_x_one-a(1))^2+(rad_y_one-b(1))^2)^0.5; radius_two = ((rad_x_two-a(1))^2+(rad_y_two-b(1))^2)^0.5; radius(COUNT) = (radius_one + radius_two)/2 %Setting Other Parameters Zero major_axis(COUNT)=0; minor_axis(COUNT)=0; angle_1(COUNT)=0; angle_2(COUNT)=0; set(handles.cord,'String',radius(COUNT)); %plotting the circle h(COUNT) = plot(rad_x(COUNT),rad_y(COUNT),'b+'); rectangle('Position',[rad_x(COUNT) - radius(COUNT), rad_y(COUNT) - radius(COUNT), 2*radius(COUNT), 2*radius(COUNT)],... 'Curvature', [1,1], 'edgecolor', 'r', 'linewidth', 1.5); % Setting Parameter PARAMETER(COUNT) = 6; guidata(hObject, handles); % --- Executes on button press in select_point_ellipse. function select_point_ellipse_Callback(hObject, eventdata, handles) % hObject handle to select_point_ellipse (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %Initialize variables global COUNT global radius global rad_x global rad_y global PARAMETER global X0_in global Y0_in global a_ellipse global b_ellipse global long_axis global short_axis global major_axis global minor_axis

Page 52: Crater detection - Report

52 iirs

if isempty(COUNT) COUNT = 0; end %Input Points for i=1:5, [p q] = ginput(1); a(i) = p; b(i) = q; hold on; plot(p,q,'r+'); set(handles.x_cord,'String',a(i)); set(handles.y_cord,'String',b(i)); %number of Circles Drawn end %Incrementing the counter COUNT = COUNT+1; %Calling Ellipse Function ellipse_t = fit_ellipse(a,b); set(handles.circ_num,'String',COUNT); %Storing Generated Data in Counters rad_x(COUNT) = X0_in; rad_y(COUNT) = Y0_in; radius(COUNT) = (a_ellipse+b_ellipse)/2; major_axis(COUNT) = long_axis; minor_axis(COUNT) = short_axis; PARAMETER(COUNT) = 9; guidata(hObject,handles); % --- Executes on button press in image_save. function image_save_Callback(hObject, eventdata, handles) % hObject handle to image_save (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %getting Pathname and Filename [filename, pathname] = uiputfile('*.png','Save Image'); newfilename = fullfile(Pathname, Filename); %Saving Image saveas(gca,newfilename); guidata(hObject,handles); % --- Executes on button press in plot_graph. function plot_graph_Callback(hObject, eventdata, handles) % hObject handle to plot_graph (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global COUNT global radius global rad_x global rad_y %Clearing Axis cla reset;

Page 53: Crater detection - Report

53 iirs

%changing Data in Kilometer rad = (radius*75)/1000 %75 for MiniSAR % Changing Radius into Diameter D = (2*rad); %Plotting Size Frequency Distribution [counter,bins] = hist(D); %checking for Zero Values size_counter = size(counter); for (i=1:size_counter) if(counter(i)<1) counter(i)=1; end end %Finding the Age modelFun = @(a,x) 10.^(a+(-3.55)*(log(x))+(0.78)*((log(x)).^2)); startingVals = 0; coefEsts = nlinfit(bins, counter, modelFun, startingVals); %Displaying the Age set(handles.age_estimate,'String',coefEsts); %Plotting SFD plot(bins,counter,'r:'); xlabel('Diameter range(in KM)'); ylabel('Number of Craters'); lsline; grid on; guidata(hObject,handles); % --- Executes on button press in save_data. function save_data_Callback(hObject, eventdata, handles) % hObject handle to save_data (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global COUNT global radius global rad_x global rad_y global PARAMETER global major_axis global minor_axis global horzi_line global vert_line global rot_ellipse global angle_1 global angle_2 %Getting Filename and Pathname [filename, pathname] = uiputfile('*.mat','Save Crater Data'); newfilename = fullfile(pathname, filename); % saving variables

Page 54: Crater detection - Report

54 iirs

save(newfilename, 'radius*','rad_x*','rad_y*','major_axis*','minor_axis*','PARAMETER*','COUNT*','horzi_line*','vert_line*','rot_ellipse*','angle_1*','angle_2*'); guidata(hObject,handles); % --- Executes on button press in clear_last. function clear_last_Callback(hObject, eventdata, handles) % hObject handle to clear_last (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global PARAMETER global COUNT global radius global rad_x global rad_y global angle_1 global angle_2 global major_axis global minor_axis %Setting PARAMETER values if COUNT>0 if (PARAMETER(COUNT)<5) PARAMETER(COUNT)=5; end for i=1:PARAMETER(COUNT) %Calling Undo Function undo; end %Clearing data from Counters radius(COUNT) = []; rad_x(COUNT) = []; rad_y(COUNT) = []; PARAMETER(COUNT) = []; angle_1(COUNT) = []; angle_2(COUNT) = []; major_axis(COUNT) = []; minor_axis(COUNT) = []; COUNT = COUNT-1; end set(handles.circ_num,'String',COUNT); guidata(hObject,handles); % --- Executes on button press in plot_save_data. function plot_save_data_Callback(hObject, eventdata, handles) % hObject handle to plot_save_data (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global PARAMETER global COUNT global radius global rad_x global rad_y global Filename_data global Pathname_data global major_axis

Page 55: Crater detection - Report

55 iirs

global minor_axis global vert_line global horzi_line global rot_ellipse global angle_1 global angle_2 %Choose the File [Filename_data, Pathname_data] = uigetfile('*.mat', 'Pick the Corresponding Data File'); %Load the Data S = load(Filename_data); %Store File Variables to workspace variables COUNT = S.COUNT; radius = S.radius; rad_x = S.rad_x; rad_y = S.rad_y; PARAMETER = S.PARAMETER; horzi_line = S.horzi_line; vert_line = S.vert_line; rot_ellipse = S.rot_ellipse; angle_1 = S.angle_1; angle_2 = S.angle_2; set(handles.circ_num,'String',COUNT); %plot from the extracted data for i=1:COUNT, if (PARAMETER(i)<9) if (PARAMETER(i)>4) hold on; plot(rad_x(i),rad_y(i),'b+'); rectangle('Position',[rad_x(i) - radius(i), rad_y(i) - radius(i), 2*radius(i), 2*radius(i)],... 'Curvature', [1,1], 'edgecolor', 'r', 'linewidth', 1.5); else hold on; %plotting the arc hold on; plot( rad_x(i),rad_y(i),'b+'); ang([rad_x(i) rad_y(i)],radius(i),[angle_1(i) angle_2(i)],'r') end else hold on; plot(horzi_line(1,:,i),horzi_line(2,:,i),'g' ); plot(rot_ellipse(1,:,i),rot_ellipse(2,:,i),'r','linewidth', 1.5 ); plot(vert_line(1,:,i),vert_line(2,:,i),'g' ); plot( rad_x,rad_y,'b+'); end end guidata(hObject,handles); % --- Executes on button press in revert_image. function revert_image_Callback(hObject, eventdata, handles) % hObject handle to revert_image (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)

Page 56: Crater detection - Report

56 iirs

global Filename global Pathname global Filename_data global Pathname_data global rad_x global rad_y global radius global COUNT global PARAMETER global vert_line global horzi_line global rot_ellipse global angle_1 global angle_2 I = fullfile(Pathname, Filename); % Appends the file path and the file name together. img = imread(I); % Reads the image and store it to a variable. imshow(img); % Displays the image. handles.picture = img; % Creates the handle for the image for modifications. %Load the Data S = load(Filename_data); %Store File Variables to workspace variables COUNT = S.COUNT; radius = S.radius; rad_x = S.rad_x; rad_y = S.rad_y; PARAMETER = S.PARAMETER; horzi_line = S.horzi_line; vert_line = S.vert_line; rot_ellipse = S.rot_ellipse; angle_1 = S.angle_1; angle_2 = S.angle_2; set(handles.circ_num,'String',COUNT); %plot from the extracted data for i=1:COUNT if (PARAMETER(i)<9) if (PARAMETER(i)>4) hold on; plot(rad_x(i),rad_y(i),'b+'); rectangle('Position',[rad_x(i) - radius(i), rad_y(i) - radius(i), 2*radius(i), 2*radius(i)],... 'Curvature', [1,1], 'edgecolor', 'r', 'linewidth', 1.5); else hold on; %plotting the arc hold on; plot( rad_x(i),rad_y(i),'b+'); ang([rad_x(i) rad_y(i)],radius(i),[angle_1(i) angle_2(i)],'r') end else hold on; plot(horzi_line(1,:,i),horzi_line(2,:,i),'g' ); plot(rot_ellipse(1,:,i),rot_ellipse(2,:,i),'r','linewidth', 1.5 );

Page 57: Crater detection - Report

57 iirs

plot(vert_line(1,:,i),vert_line(2,:,i),'g' ); plot( rad_x,rad_y,'b+'); end end guidata(hObject, handles); % Update handles structure. % --- Executes on button press in three_point_arc. function three_point_arc_Callback(hObject, eventdata, handles) % hObject handle to three_point_arc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global COUNT global radius global rad_x global rad_y global PARAMETER global major_axis global minor_axis global angle_1 global angle_2 if isempty(COUNT) COUNT = 0; end %Inoutting 3 points for i=1:3, [x y] = ginput(1); a(i) = x; b(i) = y; hold on; plot(x,y,'r+'); set(handles.x_cord,'String',a(i)); set(handles.y_cord,'String',b(i)); %number of Circles Drawn end %Incrementing Count COUNT = COUNT + 1; %printing number of Circles set(handles.circ_num,'String',COUNT); %calculating circle radii and center %slope of the lines m_1 = (b(2)-b(1))/(a(2)-a(1)); m_2 = (b(3)-b(2))/(a(3)-a(2)); %calculation of the center points rad_x(COUNT) = ((m_1)*(m_2)*(b(1)-b(3))+((m_2)*(a(1)+a(2)))-(m_1)*(a(2)+a(3)))/(2*(m_2-m_1)); rad_y(COUNT) = ((a(3)-a(1))-(b(1)+b(2))*(m_1)+(b(2)+b(3))*(m_2))/(2*(m_2-m_1)); %calculation of the radius radius(COUNT) = ((rad_x(COUNT)-a(1))^2+(rad_y(COUNT)-b(1))^2)^0.5; %Setting Major and Minor axis Blank

Page 58: Crater detection - Report

58 iirs

major_axis(COUNT)=0; minor_axis(COUNT)=0; set(handles.cord,'String',radius(COUNT)); %calculation of angles theta_1 = atan((b(1)-rad_y(COUNT))/abs((rad_x(COUNT)-a(1)))); theta_first = theta_1; theta_2 = atan((b(3)-rad_y(COUNT))/abs((a(3)-rad_x(COUNT)))); theta_second = theta_2; %Taking Cases if (a(1)<rad_x(COUNT) && theta_1>0) theta_1 = (pi-theta_1); end if (a(1)<rad_x(COUNT) && theta_1<0) theta_1 = (-pi-theta_1); end if (a(3)<rad_x(COUNT) && theta_2>0) theta_2 = (pi-theta_2); end if (a(3)<rad_x(COUNT) && theta_2<0) theta_2 = (-pi-theta_2); end if (a(1)<rad_x(COUNT) && a(3)<rad_x(COUNT) && a(2)<rad_x(COUNT)) theta_1 = (pi-theta_first); theta_2 = (pi-theta_second); end angle_1(COUNT) = theta_1; angle_2(COUNT) = theta_2; %plotting the arc hold on; set(handles.x_cord,'String',theta_1); set(handles.y_cord,'String',theta_2); h(COUNT) = plot( rad_x(COUNT),rad_y(COUNT),'b+'); ang([rad_x(COUNT) rad_y(COUNT)],radius(COUNT),[angle_1(COUNT) angle_2(COUNT)],'r') %Set the Parameter PARAMETER(COUNT)=4; guidata(hObject,handles); % --- Executes on button press in export_data. function export_data_Callback(hObject, eventdata, handles) % hObject handle to export_data (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global COUNT global rot_ellipse global horzi_line global vert_line global y_data global PARAMETER

Page 59: Crater detection - Report

59 iirs

%Initializing Variable coord = []; temp1=[]; a1=[]; %Concatenating the ellipse Data for i=1:COUNT if (PARAMETER(i)>7) temp1(:,:)=rot_ellipse(:,:,i) a1 = temp1' a2 = [NaN NaN] coord = [coord; a1] coord = [coord; a2] end end %Getting Spatial resolution res = str2num(get(handles.resolution,'String')); if isempty(res) msgbox('Spatial Resolution can not be empty'); else %Converting The co-ordinates %coord(:,2) = coord(:,2)*(-1); coord(:,1) = coord(:,1)*(res); coord(:,2) = coord(:,2)*(res); y_data = res*(y_data); coord(:,2) = (y_data - coord(:,2)); %Getting File name to Save [filename, pathname] = uiputfile('*.txt','Export Crater Co-ordinate Data'); newfilename = fullfile(pathname, filename); save(newfilename, 'coord*', '-ASCII'); %Z=0; %fname = 'hello'; %writedxf(fname,coord(1),coord(2),Z) %msgbox('hello'); end guidata(hObject,handles); function resolution_Callback(hObject, eventdata, handles) % hObject handle to resolution (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of resolution as text % str2double(get(hObject,'String')) returns contents of resolution as a double % --- Executes during object creation, after setting all properties. function resolution_CreateFcn(hObject, eventdata, handles) % hObject handle to resolution (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER.

Page 60: Crater detection - Report

60 iirs

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

Ellipse Function File (fit_ellipse.m) function ellipse_t = fit_ellipse( x,y) global COUNT global X0_in global Y0_in global PARAMETER global a_ellipse global b_ellipse global long_axis global short_axis global horzi_line global vert_line global rot_ellipse % initialize orientation_tolerance = 1e-3; % empty warning stack warning( '' ); % prepare vectors, must be column vectors x = x(:); y = y(:); % remove bias of the ellipse - to make matrix inversion more accurate. (will be added later on). mean_x = mean(x); mean_y = mean(y); x = x-mean_x; y = y-mean_y; % the estimation for the conic equation of the ellipse X = [x.^2, x.*y, y.^2, x, y ]; a = sum(X)/(X'*X); % check for warnings if ~isempty( lastwarn ) disp( 'stopped because of a warning regarding matrix inversion' ); ellipse_t = []; return end % extract parameters from the conic equation [a,b,c,d,e] = deal( a(1),a(2),a(3),a(4),a(5) ); % remove the orientation from the ellipse if ( min(abs(b/a),abs(b/c)) > orientation_tolerance ) orientation_rad = 1/2 * atan( b/(c-a) ); cos_phi = cos( orientation_rad ); sin_phi = sin( orientation_rad ); [a,b,c,d,e] = deal(... a*cos_phi^2 - b*cos_phi*sin_phi + c*sin_phi^2,... 0,...

Page 61: Crater detection - Report

61 iirs

a*sin_phi^2 + b*cos_phi*sin_phi + c*cos_phi^2,... d*cos_phi - e*sin_phi,... d*sin_phi + e*cos_phi ); [mean_x,mean_y] = deal( ... cos_phi*mean_x - sin_phi*mean_y,... sin_phi*mean_x + cos_phi*mean_y ); else orientation_rad = 0; cos_phi = cos( orientation_rad ); sin_phi = sin( orientation_rad ); end % check if conic equation represents an ellipse test = a*c; switch (1) case (test>0), status = ''; case (test==0), status = 'Parabola found'; warning( 'fit_ellipse: Did not locate an ellipse' ); case (test<0), status = 'Hyperbola found'; warning( 'fit_ellipse: Did not locate an ellipse' ); end % if we found an ellipse return it's data if (test>0) % make sure coefficients are positive as required if (a<0), [a,c,d,e] = deal( -a,-c,-d,-e ); end % final ellipse parameters X0 = mean_x - d/2/a; Y0 = mean_y - e/2/c; F = 1 + (d^2)/(4*a) + (e^2)/(4*c); [a,b] = deal( sqrt( F/a ),sqrt( F/c ) ); long_axis = 2*max(a,b); short_axis = 2*min(a,b); % rotate the axes backwards to find the center point of the original TILTED ellipse R = [ cos_phi sin_phi; -sin_phi cos_phi ]; P_in = R * [X0;Y0]; X0_in = P_in(1); Y0_in = P_in(2); a_ellipse = a; b_ellipse = b; % pack ellipse into a structure ellipse_t = struct( ... 'a',a,... 'b',b,... 'phi',orientation_rad,... 'X0',X0,... 'Y0',Y0,... 'X0_in',X0_in,... 'Y0_in',Y0_in,... 'long_axis',long_axis,... 'short_axis',short_axis,... 'status','' ); else % report an empty structure ellipse_t = struct( ... 'a',[],...

Page 62: Crater detection - Report

62 iirs

'b',[],... 'phi',[],... 'X0',[],... 'Y0',[],... 'X0_in',[],... 'Y0_in',[],... 'long_axis',[],... 'short_axis',[],... 'status',status ); end hold on; % rotation matrix to rotate the axes with respect to an angle phi R = [ cos_phi sin_phi; -sin_phi cos_phi ]; % the axes ver_line = [ [X0 X0]; Y0+b*[-1 1] ]; horz_line = [ X0+a*[-1 1]; [Y0 Y0] ]; new_ver_line = R*ver_line; new_horz_line = R*horz_line; % the ellipse theta_r = linspace(0,2*pi); ellipse_x_r = X0 + a*cos( theta_r ); ellipse_y_r = Y0 + b*sin( theta_r ); rotated_ellipse = R * [ellipse_x_r;ellipse_y_r]; %converting 2-D Matrices into 3-D Matrices vert_line(:,:,COUNT) = new_ver_line(:,:); horzi_line(:,:,COUNT) = new_horz_line(:,:); rot_ellipse(:,:,COUNT) = rotated_ellipse(:,:); % draw plot( horzi_line(1,:,COUNT),horzi_line(2,:,COUNT),'g' ); plot( rot_ellipse(1,:,COUNT),rot_ellipse(2,:,COUNT),'r','linewidth', 1.5 ); plot( vert_line(1,:,COUNT),vert_line(2,:,COUNT),'g' ); plot( X0_in,Y0_in,'b+'); end

Angle Function(ang.m) function h = ang(centre,radius,span,style) % ANG % Plots an angle arc with specified position and circumference. % Example: % ang([3 2],5,[0 pi/2],'k-') % Plots an arc with centre (3,2) and radius (5) that represents % The angle specified from 0 to pi/2, and with the preferred style 'k-'. theta = linspace(span(1),span(2),100); rho = ones(1,100) * radius; [x,y] = pol2cart(theta,rho); x = x + centre(1); y = y + centre(2); h = plot(x,y,style,'linewidth', 1.5); end

Page 63: Crater detection - Report

63 iirs

Hough Transformation Function(hough.m) function [accum, varargout] = CircularHough_Grd(img, radrange, varargin) %Detect circular shapes in a grayscale image. Resolve their center %positions and radii. % % [accum, circen, cirrad, dbg_LMmask] = CircularHough_Grd( % img, radrange, grdthres, fltr4LM_R, multirad, fltr4accum) % Circular Hough transform based on the gradient field of an image. % NOTE: Operates on grayscale images, NOT B/W bitmaps. % NO loops in the implementation of Circular Hough transform, % which means faster operation but at the same time larger % memory consumption. % %%%%%%%% INPUT: (img, radrange, grdthres, fltr4LM_R, multirad, fltr4accum) % % img: A 2-D grayscale image (NO B/W bitmap) % % radrange: The possible minimum and maximum radii of the circles % to be searched, in the format of % [minimum_radius , maximum_radius] (unit: pixels) % **NOTE**: A smaller range saves computational time and % memory. % % grdthres: (Optional, default is 10, must be non-negative) %%%%%%%% Arguments and parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Validation of arguments if ndims(img) ~= 2 || ~isnumeric(img), error('CircularHough_Grd: ''img'' has to be 2 dimensional'); end if ~all(size(img) >= 32), error('CircularHough_Grd: ''img'' has to be larger than 32-by-32'); end if numel(radrange) ~= 2 || ~isnumeric(radrange), error(['CircularHough_Grd: ''radrange'' has to be ', ... 'a two-element vector']); end prm_r_range = sort(max( [0,0;radrange(1),radrange(2)] )); % Parameters (default values) prm_grdthres = 10; prm_fltrLM_R = 8; prm_multirad = 0.5; func_compu_cen = true; func_compu_radii = true; % Validation of arguments vap_grdthres = 1; if nargin > (1 + vap_grdthres), if isnumeric(varargin{vap_grdthres}) && ... varargin{vap_grdthres}(1) >= 0, prm_grdthres = varargin{vap_grdthres}(1); else error(['CircularHough_Grd: ''grdthres'' has to be ', ... 'a non-negative number']); end end

Page 64: Crater detection - Report

64 iirs

vap_fltr4LM = 2; % filter for the search of local maxima if nargin > (1 + vap_fltr4LM), if isnumeric(varargin{vap_fltr4LM}) && varargin{vap_fltr4LM}(1) >= 3, prm_fltrLM_R = varargin{vap_fltr4LM}(1); else error(['CircularHough_Grd: ''fltr4LM_R'' has to be ', ... 'larger than or equal to 3']); end end vap_multirad = 3; if nargin > (1 + vap_multirad), if isnumeric(varargin{vap_multirad}) && ... varargin{vap_multirad}(1) >= 0.1 && ... varargin{vap_multirad}(1) <= 1, prm_multirad = varargin{vap_multirad}(1); else error(['CircularHough_Grd: ''multirad'' has to be ', ... 'within the range [0.1, 1]']); end end vap_fltr4accum = 4; % filter for smoothing the accumulation array if nargin > (1 + vap_fltr4accum), if isnumeric(varargin{vap_fltr4accum}) && ... ndims(varargin{vap_fltr4accum}) == 2 && ... all(size(varargin{vap_fltr4accum}) >= 3), fltr4accum = varargin{vap_fltr4accum}; else error(['CircularHough_Grd: ''fltr4accum'' has to be ', ... 'a 2-D matrix with a minimum size of 3-by-3']); end else % Default filter (5-by-5) fltr4accum = ones(5,5); fltr4accum(2:4,2:4) = 2; fltr4accum(3,3) = 6; end func_compu_cen = ( nargout > 1 ); func_compu_radii = ( nargout > 2 ); % Reserved parameters dbg_on = false; % debug information dbg_bfigno = 4; if nargout > 3, dbg_on = true; end %%%%%%%% Building accumulation array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Convert the image to single if it is not of % class float (single or double) img_is_double = isa(img, 'double'); if ~(img_is_double || isa(img, 'single')), imgf = single(img); end % Compute the gradient and the magnitude of gradient

Page 65: Crater detection - Report

65 iirs

if img_is_double, [grdx, grdy] = gradient(img); else [grdx, grdy] = gradient(imgf); end grdmag = sqrt(grdx.^2 + grdy.^2); % Get the linear indices, as well as the subscripts, of the pixels % whose gradient magnitudes are larger than the given threshold grdmasklin = find(grdmag > prm_grdthres); [grdmask_IdxI, grdmask_IdxJ] = ind2sub(size(grdmag), grdmasklin); % Compute the linear indices (as well as the subscripts) of % all the votings to the accumulation array. % The Matlab function 'accumarray' accepts only double variable, % so all indices are forced into double at this point. % A row in matrix 'lin2accum_aJ' contains the J indices (into the % accumulation array) of all the votings that are introduced by a % same pixel in the image. Similarly with matrix 'lin2accum_aI'. rr_4linaccum = double( prm_r_range ); linaccum_dr = [ (-rr_4linaccum(2) + 0.5) : -rr_4linaccum(1) , ... (rr_4linaccum(1) + 0.5) : rr_4linaccum(2) ]; lin2accum_aJ = floor( ... double(grdx(grdmasklin)./grdmag(grdmasklin)) * linaccum_dr + ... repmat( double(grdmask_IdxJ)+0.5 , [1,length(linaccum_dr)] ) ... ); lin2accum_aI = floor( ... double(grdy(grdmasklin)./grdmag(grdmasklin)) * linaccum_dr + ... repmat( double(grdmask_IdxI)+0.5 , [1,length(linaccum_dr)] ) ... ); % Clip the votings that are out of the accumulation array mask_valid_aJaI = ... lin2accum_aJ > 0 & lin2accum_aJ < (size(grdmag,2) + 1) & ... lin2accum_aI > 0 & lin2accum_aI < (size(grdmag,1) + 1); mask_valid_aJaI_reverse = ~ mask_valid_aJaI; lin2accum_aJ = lin2accum_aJ .* mask_valid_aJaI + mask_valid_aJaI_reverse; lin2accum_aI = lin2accum_aI .* mask_valid_aJaI + mask_valid_aJaI_reverse; clear mask_valid_aJaI_reverse; % Linear indices (of the votings) into the accumulation array lin2accum = sub2ind( size(grdmag), lin2accum_aI, lin2accum_aJ ); lin2accum_size = size( lin2accum ); lin2accum = reshape( lin2accum, [numel(lin2accum),1] ); clear lin2accum_aI lin2accum_aJ; % Weights of the votings, currently using the gradient maginitudes % but in fact any scheme can be used (application dependent) weight4accum = ... repmat( double(grdmag(grdmasklin)) , [lin2accum_size(2),1] ) .* ... mask_valid_aJaI(:); clear mask_valid_aJaI; % Build the accumulation array using Matlab function 'accumarray' accum = accumarray( lin2accum , weight4accum ); accum = [ accum ; zeros( numel(grdmag) - numel(accum) , 1 ) ];

Page 66: Crater detection - Report

66 iirs

accum = reshape( accum, size(grdmag) ); %%%%%%%% Locating local maxima in the accumulation array %%%%%%%%%%%% % Stop if no need to locate the center positions of circles if ~func_compu_cen, return; end clear lin2accum weight4accum; % Parameters to locate the local maxima in the accumulation array % -- Segmentation of 'accum' before locating LM prm_useaoi = true; prm_aoithres_s = 2; prm_aoiminsize = floor(min([ min(size(accum)) * 0.25, ... prm_r_range(2) * 1.5 ])); % -- Filter for searching for local maxima prm_fltrLM_s = 1.35; prm_fltrLM_r = ceil( prm_fltrLM_R * 0.6 ); prm_fltrLM_npix = max([ 6, ceil((prm_fltrLM_R/2)^1.8) ]); % -- Lower bound of the intensity of local maxima prm_LM_LoBndRa = 0.2; % minimum ratio of LM to the max of 'accum' % Smooth the accumulation array fltr4accum = fltr4accum / sum(fltr4accum(:)); accum = filter2( fltr4accum, accum ); % Select a number of Areas-Of-Interest from the accumulation array if prm_useaoi, % Threshold value for 'accum' prm_llm_thres1 = prm_grdthres * prm_aoithres_s; % Thresholding over the accumulation array accummask = ( accum > prm_llm_thres1 ); % Segmentation over the mask [accumlabel, accum_nRgn] = bwlabel( accummask, 8 ); % Select AOIs from segmented regions accumAOI = ones(0,4); for k = 1 : accum_nRgn, accumrgn_lin = find( accumlabel == k ); [accumrgn_IdxI, accumrgn_IdxJ] = ... ind2sub( size(accumlabel), accumrgn_lin ); rgn_top = min( accumrgn_IdxI ); rgn_bottom = max( accumrgn_IdxI ); rgn_left = min( accumrgn_IdxJ ); rgn_right = max( accumrgn_IdxJ ); % The AOIs selected must satisfy a minimum size if ( (rgn_right - rgn_left + 1) >= prm_aoiminsize && ... (rgn_bottom - rgn_top + 1) >= prm_aoiminsize ), accumAOI = [ accumAOI; ... rgn_top, rgn_bottom, rgn_left, rgn_right ]; end end else

Page 67: Crater detection - Report

67 iirs

% Whole accumulation array as the one AOI accumAOI = [1, size(accum,1), 1, size(accum,2)]; end % Thresholding of 'accum' by a lower bound prm_LM_LoBnd = max(accum(:)) * prm_LM_LoBndRa; % Build the filter for searching for local maxima fltr4LM = zeros(2 * prm_fltrLM_R + 1); [mesh4fLM_x, mesh4fLM_y] = meshgrid(-prm_fltrLM_R : prm_fltrLM_R); mesh4fLM_r = sqrt( mesh4fLM_x.^2 + mesh4fLM_y.^2 ); fltr4LM_mask = ... ( mesh4fLM_r > prm_fltrLM_r & mesh4fLM_r <= prm_fltrLM_R ); fltr4LM = fltr4LM - ... fltr4LM_mask * (prm_fltrLM_s / sum(fltr4LM_mask(:))); if prm_fltrLM_R >= 4, fltr4LM_mask = ( mesh4fLM_r < (prm_fltrLM_r - 1) ); else fltr4LM_mask = ( mesh4fLM_r < prm_fltrLM_r ); end fltr4LM = fltr4LM + fltr4LM_mask / sum(fltr4LM_mask(:)); % **** Debug code (begin) if dbg_on, dbg_LMmask = zeros(size(accum)); end % **** Debug code (end) % For each of the AOIs selected, locate the local maxima circen = zeros(0,2); for k = 1 : size(accumAOI, 1), aoi = accumAOI(k,:); % just for referencing convenience % Thresholding of 'accum' by a lower bound accumaoi_LBMask = ... ( accum(aoi(1):aoi(2), aoi(3):aoi(4)) > prm_LM_LoBnd ); % Apply the local maxima filter candLM = conv2( accum(aoi(1):aoi(2), aoi(3):aoi(4)) , ... fltr4LM , 'same' ); candLM_mask = ( candLM > 0 ); % Clear the margins of 'candLM_mask' candLM_mask([1:prm_fltrLM_R, (end-prm_fltrLM_R+1):end], :) = 0; candLM_mask(:, [1:prm_fltrLM_R, (end-prm_fltrLM_R+1):end]) = 0; % **** Debug code (begin) if dbg_on, dbg_LMmask(aoi(1):aoi(2), aoi(3):aoi(4)) = ... dbg_LMmask(aoi(1):aoi(2), aoi(3):aoi(4)) + ... accumaoi_LBMask + 2 * candLM_mask; end % **** Debug code (end) % Group the local maxima candidates by adjacency, compute the % centroid position for each group and take that as the center % of one circle detected

Page 68: Crater detection - Report

68 iirs

[candLM_label, candLM_nRgn] = bwlabel( candLM_mask, 8 ); for ilabel = 1 : candLM_nRgn, % Indices (to current AOI) of the pixels in the group candgrp_masklin = find( candLM_label == ilabel ); [candgrp_IdxI, candgrp_IdxJ] = ... ind2sub( size(candLM_label) , candgrp_masklin ); % Indices (to 'accum') of the pixels in the group candgrp_IdxI = candgrp_IdxI + ( aoi(1) - 1 ); candgrp_IdxJ = candgrp_IdxJ + ( aoi(3) - 1 ); candgrp_idx2acm = ... sub2ind( size(accum) , candgrp_IdxI , candgrp_IdxJ ); % Minimum number of qulified pixels in the group if sum(accumaoi_LBMask(candgrp_masklin)) < prm_fltrLM_npix, continue; end % Compute the centroid position candgrp_acmsum = sum( accum(candgrp_idx2acm) ); cc_x = sum( candgrp_IdxJ .* accum(candgrp_idx2acm) ) / ... candgrp_acmsum; cc_y = sum( candgrp_IdxI .* accum(candgrp_idx2acm) ) / ... candgrp_acmsum; circen = [circen; cc_x, cc_y]; end end % **** Debug code (begin) if dbg_on, figure(dbg_bfigno); imagesc(dbg_LMmask); axis image; title('Generated map of local maxima'); if size(accumAOI, 1) == 1, figure(dbg_bfigno+1); surf(candLM, 'EdgeColor', 'none'); axis ij; title('Accumulation array after local maximum filtering'); end end % **** Debug code (end) %%%%%%%% Estimation of the Radii of Circles %%%%%%%%%%%% % Stop if no need to estimate the radii of circles if ~func_compu_radii, varargout{1} = circen; return; end % Parameters for the estimation of the radii of circles fltr4SgnCv = [2 1 1]; fltr4SgnCv = fltr4SgnCv / sum(fltr4SgnCv); % Find circle's radius using its signature curve cirrad = zeros( size(circen,1), 1 ); for k = 1 : size(circen,1), % Neighborhood region of the circle for building the sgn. curve

Page 69: Crater detection - Report

69 iirs

circen_round = round( circen(k,:) ); SCvR_I0 = circen_round(2) - prm_r_range(2) - 1; if SCvR_I0 < 1, SCvR_I0 = 1; end SCvR_I1 = circen_round(2) + prm_r_range(2) + 1; if SCvR_I1 > size(grdx,1), SCvR_I1 = size(grdx,1); end SCvR_J0 = circen_round(1) - prm_r_range(2) - 1; if SCvR_J0 < 1, SCvR_J0 = 1; end SCvR_J1 = circen_round(1) + prm_r_range(2) + 1; if SCvR_J1 > size(grdx,2), SCvR_J1 = size(grdx,2); end % Build the sgn. curve SgnCvMat_dx = repmat( (SCvR_J0:SCvR_J1) - circen(k,1) , ... [SCvR_I1 - SCvR_I0 + 1 , 1] ); SgnCvMat_dy = repmat( (SCvR_I0:SCvR_I1)' - circen(k,2) , ... [1 , SCvR_J1 - SCvR_J0 + 1] ); SgnCvMat_r = sqrt( SgnCvMat_dx .^2 + SgnCvMat_dy .^2 ); SgnCvMat_rp1 = round(SgnCvMat_r) + 1; f4SgnCv = abs( ... double(grdx(SCvR_I0:SCvR_I1, SCvR_J0:SCvR_J1)) .* SgnCvMat_dx + ... double(grdy(SCvR_I0:SCvR_I1, SCvR_J0:SCvR_J1)) .* SgnCvMat_dy ... ) ./ SgnCvMat_r; SgnCv = accumarray( SgnCvMat_rp1(:) , f4SgnCv(:) ); SgnCv_Cnt = accumarray( SgnCvMat_rp1(:) , ones(numel(f4SgnCv),1) ); SgnCv_Cnt = SgnCv_Cnt + (SgnCv_Cnt == 0); SgnCv = SgnCv ./ SgnCv_Cnt; % Suppress the undesired entries in the sgn. curve % -- Radii that correspond to short arcs SgnCv = SgnCv .* ( SgnCv_Cnt >= (pi/4 * [0:(numel(SgnCv_Cnt)-1)]') ); % -- Radii that are out of the given range SgnCv( 1 : (round(prm_r_range(1))+1) ) = 0; SgnCv( (round(prm_r_range(2))+1) : end ) = 0; % Get rid of the zero radius entry in the array SgnCv = SgnCv(2:end); % Smooth the sgn. curve SgnCv = filtfilt( fltr4SgnCv , [1] , SgnCv ); % Get the maximum value in the sgn. curve SgnCv_max = max(SgnCv); if SgnCv_max <= 0, cirrad(k) = 0; continue; end % Find the local maxima in sgn. curve by 1st order derivatives % -- Mark the ascending edges in the sgn. curve as 1s and % -- descending edges as 0s SgnCv_AscEdg = ( SgnCv(2:end) - SgnCv(1:(end-1)) ) > 0; % -- Mark the transition (ascending to descending) regions

Page 70: Crater detection - Report

70 iirs

SgnCv_LMmask = [ 0; 0; SgnCv_AscEdg(1:(end-2)) ] & (~SgnCv_AscEdg); SgnCv_LMmask = SgnCv_LMmask & [ SgnCv_LMmask(2:end) ; 0 ]; % Incorporate the minimum value requirement SgnCv_LMmask = SgnCv_LMmask & ... ( SgnCv(1:(end-1)) >= (prm_multirad * SgnCv_max) ); % Get the positions of the peaks SgnCv_LMPos = sort( find(SgnCv_LMmask) ); % Save the detected radii if isempty(SgnCv_LMPos), cirrad(k) = 0; else cirrad(k) = SgnCv_LMPos(end); for i_radii = (length(SgnCv_LMPos) - 1) : -1 : 1, circen = [ circen; circen(k,:) ]; cirrad = [ cirrad; SgnCv_LMPos(i_radii) ]; end end end % Output varargout{1} = circen; varargout{2} = cirrad; if nargout > 3, varargout{3} = dbg_LMmask; end

****