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

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