changed some variables to defines
[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( 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                 if( lastPosition > 0)
225                 {       
226                         // Find the rate of expansion and convert to mm. Will give a negative result for compression.
227                         *value = (average - lastPosition) * SCALE;
228                         lastPosition = average; // Current position now becomes the last position
229                 }
230         }
231         return result;
232 }
233
234  /**
235  * Read the dilatometer image. The value changed will correspond to the new location of the edge.
236  * @param val - Will store the read value if successful
237  * @returns true on successful read
238  */
239 bool Dilatometer_Read(int id, double * value)
240 {
241         bool result = Dilatometer_GetExpansion(value, SAMPLES);
242         return result;
243 }
244
245 /**
246  * Initialise the dilatometer
247  */
248 bool Dilatometer_Init(const char * name, int id)
249 {
250         // Make an initial reading (will allocate memory the first time only).
251         double val;
252         lastPosition = 0;  // Reset the last position
253         bool result = Dilatometer_GetExpansion(&val, 1); 
254         return result;
255 }
256
257 // Overlays a line over the given edge position
258 void Draw_Edge(double edge)
259 {
260         CvScalar value;
261         value.val[0]=244;
262         for( int i = 0; i < g_srcGray->rows; i++)
263         {
264                 cvSet2D(g_edges,i,edge,value);
265         }
266         cvShowImage("display", g_edges);
267         cvWaitKey(0);   
268         //cvSaveImage("test_edge_avg.jpg",g_edges,0);
269 }
270
271 /* // Test algorithm
272 static void Dilatometer_GetImageTest( )
273 {       
274         //Generates Test image
275         //Dilatometer_TestImage();
276         
277         //Load Test image
278         g_srcGray = cvLoadImageM ("testimage4.jpg",CV_LOAD_IMAGE_GRAYSCALE );
279 }*/
280
281 /**
282  * For testing purposes
283  */
284 /*int main(int argc, char ** argv)
285 {
286         //cvNamedWindow( "display", CV_WINDOW_AUTOSIZE );// Create a window for display.
287         //gettimeofday(&start, NULL);
288         test_left = 100;
289         test_right = 500;
290         Dilatometer_Init();
291         
292         cvNamedWindow( "display", CV_WINDOW_AUTOSIZE);
293         //double width;
294         
295         double edge;
296         Dilatometer_GetEdge(&edge,20000);
297         //For testing purposes, overlay the given average line over the image
298         //Draw_Edge(edge);
299         
300         cvDestroyWindow("display");
301
302         Dilatometer_Cleanup();
303 }*/
304

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