Chapter 02-1: Calculate the distance between two points


Chapter02-1 descripes a simple function to calculate the distance between two points. In this chapter I'm using the function instead of the macro method, because the functions can be used more versatile in plugins and macros. Finally you want to do something with the detected cornerpoints in Chapter01. In this case for example calculating the distance between two points.


Step 01: The function distance_point_point(xpoint1, ypoint1, xpoint2, ypoint2)

function distance_point_point(xpoint1, ypoint1, xpoint2, ypoint2){

    dx = xpoint2-xpoint1;
    dy = ypoint2-ypoint1;
    distance = sqrt(dx*dx + dy*dy);
    return distance;
   
}


This function takes as arguments the x/y - coordinates of two points. With the given points the function calculates delta x and delta y. And finally the distance with the well known theorem of Pythagoras. The return value is of course the distance between the two points.

Step 02: Macro example with the distance_point_point function

Some simple code sample for the imagej macro language. Open any image, make two points with the multi-point selection tool, copy the code into a new imagej text window and run the macro.


//+++++++++++ STEP 00: DESCRIPTION ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//This macro calculates the distance between to points. Open a image, then make two points with the
// "multi-point" selection tool. Copy this code to a new text window and click the Run Macro menu
// command.


//+++++++++++ STEP 00 DECLARATIONEN +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

function distance_point_point(xpoint1, ypoint1, xpoint2, ypoint2);

//+++++++++++ STEP 01 MAIN PROGRAMM +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

getSelectionCoordinates(x,y);
distance = distance_point_point(x[0],y[0],x[1],y[1]);
print("Distance point to point: ", distance);



//+++++++++++ SUBROUTINES +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++ Function: distance_point_point ++++++++++++++++++++++++++++++++++++++++++++++++++++++

function distance_point_point(xpoint1, ypoint1, xpoint2, ypoint2) {
    dx = xpoint2-xpoint1;
    dy = ypoint2-ypoint1;
    distance = sqrt(dx*dx + dy*dy);
    return distance;
}



Step 03: Enjoy the results



chapter02-1_step03.gif

The Log window shows you the distance in pixels. For realworld measurements you have to calibrate the pixelsize. At this point it is important to know what format your pixel on the sensor has. You have to find out, whether it is square or rectangular shaped. At this time I don't want to dig to deep in to measuring. At this point it is just the basic to calculate the distance between two points.