Update dilatometer.c
[matches/MCTX3420.git] / server / sensors / dilatometer.c
1 /**
2  * @file dilatometer.c
3  * @purpose Implementation of dilatometer related functions
4  */
5
6 #include "cv.h"
7 #include "highgui_c.h"
8 #include "dilatometer.h"
9 #include <math.h>
10
11 // test positions
12 static double test_left, test_right;
13
14 // Remembers the last position to measure rate of expansion
15 static double lastPosition;
16
17
18 /** Buffers for storing image data.  **/
19 static CvMat * g_srcRGB  = NULL;        // Source Image
20 static CvMat * g_srcGray = NULL;        // Gray scale of source image
21 static CvMat * g_edges   = NULL;        // Detected Edges
22
23 /** Pointers for capturing image **/
24 //static CvCapture * g_capture = NULL;
25 //static IplImage * frame  = NULL;      // This is required as you can not use capture with CvMat in C
26
27
28 /**
29  * Create a test image using left as left edge and right as right edge positions
30  */
31 void Dilatometer_TestImage()
32 {
33         
34         g_srcRGB = cvCreateMat(480, 640, CV_8UC3);
35
36         for( int x = 0; x < 640; ++x)
37         {
38                 for (int y = 0; y < 480; ++y)
39                 {
40                         CvScalar s; 
41                         for( int i = 0; i < 3; ++i)
42                         {
43                                 s.val[i]  =  210 + (rand() % 1000) * 1e-0 - (rand() % 1000) * 1e-0;
44                                 // Produce an exponential decay around left edge
45                                 if( x < test_left)
46                                         s.val[i] *= exp( (x - test_left) / 25);
47                                 else if( x < 320)
48                                         s.val[i] *= exp( (test_left - x) / 25); 
49                                 // Produce an exponential decay around right edge
50                                 else if( x < test_right)
51                                         s.val[i] *= exp( (x - test_right) / 25); 
52                                 else
53                                         s.val[i] *= exp( (test_right - x) / 25);                                
54                         }       
55                         cvSet2D(g_srcRGB,y,x,s);
56                 }
57                 
58         }
59         if (g_srcGray == NULL)
60         {
61                 g_srcGray = cvCreateMat(g_srcRGB->rows,g_srcRGB->cols,CV_8UC1);
62         }
63         cvCvtColor(g_srcRGB,g_srcGray,CV_RGB2GRAY);
64 }       
65
66 /**
67  * Cleanup Dilatometer pointers
68  */
69 bool Dilatometer_Cleanup(int id)
70 {
71         //if (g_capture != NULL)
72         //      cvReleaseCapture(&g_capture);
73         //if (frame != NULL)
74         //      cvReleaseImageHeader(&frame);
75
76         //if (g_srcRGB != NULL)
77         //      cvReleaseMat(&g_srcRGB);        // Causing run time error in cvReleaseMat
78         if (g_srcGray != NULL)
79                 cvReleaseMat(&g_srcGray);
80         if (g_edges != NULL)
81                 cvReleaseMat(&g_edges);
82         return true;
83 }
84
85 /**
86  * Get an image from the Dilatometer. Replaced by Camera_GetImage in image.c
87  */
88 /*static bool Dilatometer_GetImage()
89 {       
90         bool result = true;
91         // If more than one camera is connected, then input needs to be determined, however the camera ID may change after being unplugged
92         if( g_capture == NULL)
93         {
94                 g_capture = cvCreateCameraCapture(0);
95                 //If cvCreateCameraCapture returns NULL there is an error with the camera
96                 if( g_capture == NULL)
97                 {
98                         result = false;
99                         return;
100                 }
101         }
102
103         // Get the frame and convert it to CvMat
104         frame =  cvQueryFrame(g_capture);
105         CvMat stub;
106         g_srcRGB = cvGetMat(frame,&stub,0,0);
107
108         if( g_srcRGB == NULL)
109                 result = false;
110         
111         // Convert the image to grayscale
112         if (g_srcGray == NULL)
113         {
114                 g_srcGray = cvCreateMat(g_srcRGB->rows,g_srcRGB->cols,CV_8UC1);
115         }
116
117         cvCvtColor(g_srcRGB,g_srcGray,CV_RGB2GRAY);
118         
119         return result;
120 }*/
121
122 void CannyThreshold()
123 {
124         // Convert the RGB source file to grayscale
125         cvCvtColor(g_srcRGB,g_srcGray,CV_RGB2GRAY);
126
127         if ( g_edges == NULL)
128         {
129                 g_edges = cvCreateMat(g_srcGray->rows,g_srcGray->cols,CV_8UC1);
130         }
131         
132         // Commented out lines are used during testing to show the image to screen, can also save the test images
133         //cvShowImage("display", g_srcGray);
134         //cvWaitKey(0);         
135         
136         // Reduce noise with a kernel blurxblur. Input the grayscale source image, output to edges. (0's mean it's determined from kernel sizes)
137         cvSmooth( g_srcGray, g_edges, CV_GAUSSIAN, BLUR, BLUR ,0 ,0 );
138         
139         //Save the image
140         //cvSaveImage("test_blurred.jpg",g_edges,0);
141
142         //cvShowImage("display", g_edges);
143         //cvWaitKey(0); 
144
145         // Find the edges in the image
146         cvCanny( g_edges, g_edges, LOWTHRESHOLD, LOWTHRESHOLD*RATIO, KERNELSIZE );
147         
148         //Save the image
149         //cvSaveImage("test_edge.jpg",g_edges,0);
150
151         //cvShowImage("display", g_edges);
152         //cvWaitKey(0);         
153
154 }
155
156  /**
157  * Read the dilatometer image. The value changed will correspond to the rate of expansion. If no edge is found then 
158  * @param val - Will store the read value if successful
159  * @param samples - Number of rows to scan (increasing will slow down performance!)
160  * @returns true on successful read
161  */
162 bool Dilatometer_GetExpansion( int id, double * value, int samples)
163 {
164         bool result = false; 
165         double average = 0;
166         // Get the image from the camera
167         result = Camera_GetImage( 0, 1600, 1200 ,&g_srcRGB); // Get a 1600x1200 image and place it into src
168
169         // If an error occured when capturing image then return
170         if (!result)
171                 return result;
172
173         // Apply the Canny Edge theorem to the image
174         CannyThreshold();
175
176         int width = g_edges->cols;
177         int height = g_edges->rows;
178         
179         // If the number of samples is greater than the image height, sample every row
180         if( samples > height)
181         {
182                 samples = height;
183         }
184         
185         int sample_height;
186         int num_edges = 0;      // Number of edges found. if each sample location has an edge, then num_edges = samples
187
188         for (int i=0; i<samples; i++)
189         {
190                 // Determine the position in the rows to find the edges. 
191                 // This will give you a number of evenly spaced samples
192                 sample_height = ceil(height * (i + 1) / samples) -1;
193                 
194                 // Need to go through each pixel of a row and find all the locations of a line. If there is more than one pixel, average it. note this only works if the canny edge algorithm returns lines about the actual line (no outliers).
195                 
196                 int edge_location=0;
197                 int num=0;
198                 for ( int col = 0; col < width; col++)
199                 {
200                         // Count the number of points
201                         // Get the threshold of the pixel at the current location
202                         CvScalar value = cvGet2D(g_edges, sample_height, col);
203                         if( value.val[0]> THRES)
204                         {
205                                 edge_location += col;
206                                 num++;
207                         }
208                 }
209                 if( num > 0)
210                 {
211                         average += ( edge_location / num );
212                         num_edges++;
213                 }
214         }
215         if (num_edges > 0)
216                 average /= num_edges;
217         else
218                 return result;  // As no edges were found
219         
220         if( average > 0)
221         {       
222                 result = true; // Successfully found an edge
223                 // If the experiment has already been initialised
224                 switch (id)
225                 {
226                         case DIL_POS:
227                                 *value = average*SCALE;
228                                 return result;
229                         case DIL_DIFF:
230                                 if( lastPosition > 0)
231                                 {       
232                                         // Find the rate of expansion and convert to mm. Will give a negative result for compression.
233                                         *value = (average - lastPosition) * SCALE *2;
234                                         lastPosition = average; // Current position now becomes the last position
235                                 }
236                                 return result;
237                         default:
238                                 return false;           }
239         }
240         return result;
241 }
242
243  /**
244  * Read the dilatometer image. The value changed will correspond to the new location of the edge.
245  * @param val - Will store the read value if successful
246  * @returns true on successful read
247  */
248 bool Dilatometer_Read(int id, double * value)
249 {
250         bool result = Dilatometer_GetExpansion(id, value, SAMPLES);
251         return result;
252 }
253
254 /**
255  * Initialise the dilatometer
256  */
257 bool Dilatometer_Init(const char * name, int id)
258 {
259         // Make an initial reading (will allocate memory the first time only).
260         double val;
261         lastPosition = 0;  // Reset the last position
262         bool result = Dilatometer_GetExpansion(DIL_POS, &val, 1); 
263         return result;
264 }
265
266 // Overlays a line over the given edge position
267 void Draw_Edge(double edge)
268 {
269         CvScalar value;
270         value.val[0]=244;
271         for( int i = 0; i < g_srcGray->rows; i++)
272         {
273                 cvSet2D(g_edges,i,edge,value);
274         }
275         cvShowImage("display", g_edges);
276         cvWaitKey(0);   
277         //cvSaveImage("test_edge_avg.jpg",g_edges,0);
278 }
279
280 /* // Test algorithm
281 static void Dilatometer_GetImageTest( )
282 {       
283         //Generates Test image
284         //Dilatometer_TestImage();
285         
286         //Load Test image
287         g_srcGray = cvLoadImageM ("testimage4.jpg",CV_LOAD_IMAGE_GRAYSCALE );
288 }*/
289
290 /**
291  * For testing purposes
292  */
293 /*int main(int argc, char ** argv)
294 {
295         //cvNamedWindow( "display", CV_WINDOW_AUTOSIZE );// Create a window for display.
296         //gettimeofday(&start, NULL);
297         test_left = 100;
298         test_right = 500;
299         Dilatometer_Init();
300         
301         cvNamedWindow( "display", CV_WINDOW_AUTOSIZE);
302         //double width;
303         
304         double edge;
305         Dilatometer_GetEdge(&edge,20000);
306         //For testing purposes, overlay the given average line over the image
307         //Draw_Edge(edge);
308         
309         cvDestroyWindow("display");
310
311         Dilatometer_Cleanup();
312 }*/
313

UCC git Repository :: git.ucc.asn.au