7a85878da1ec28466d6f71d757384f56cfb11e83
[matches/MCTX3420.git] / testing / Camera / dilatometer / 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 // Canny Edge algorithm variables
15 int blur = 5;
16 int lowThreshold = 30;
17 int ratio = 3;
18 int kernel_size = 3;
19
20 /** Buffers for storing image data.  **/
21 static CvMat * g_srcRGB  = NULL;        // Source Image
22 static CvMat * g_srcGray = NULL;        // Gray scale of source image
23 static CvMat * g_edges   = NULL;        // Detected Edges
24
25 /** Pointers for capturing image **/
26 static CvCapture * g_capture = NULL;
27 static IplImage * frame  = NULL;        // This is required as you can not use capture with CvMat in C
28
29
30 /**
31  * Create a test image using left as left edge and right as right edge positions
32  */
33 void Dilatometer_TestImage()
34 {
35         
36         g_srcRGB = cvCreateMat(480, 640, CV_8UC3);
37
38         for( int x = 0; x < 640; ++x)
39         {
40                 for (int y = 0; y < 480; ++y)
41                 {
42                         CvScalar s; 
43                         for( int i = 0; i < 3; ++i)
44                         {
45                                 s.val[i]  =  210 + (rand() % 1000) * 1e-0 - (rand() % 1000) * 1e-0;
46                                 // Produce an exponential decay around left edge
47                                 if( x < test_left)
48                                         s.val[i] *= exp( (x - test_left) / 25);
49                                 else if( x < 320)
50                                         s.val[i] *= exp( (test_left - x) / 25); 
51                                 // Produce an exponential decay around right edge
52                                 else if( x < test_right)
53                                         s.val[i] *= exp( (x - test_right) / 25); 
54                                 else
55                                         s.val[i] *= exp( (test_right - x) / 25);                                
56                         }       
57                         cvSet2D(g_srcRGB,y,x,s);
58                 }
59                 
60         }
61         if (g_srcGray == NULL)
62         {
63                 g_srcGray = cvCreateMat(g_srcRGB->rows,g_srcRGB->cols,CV_8UC1);
64         }
65         cvCvtColor(g_srcRGB,g_srcGray,CV_RGB2GRAY);
66 }       
67
68 /**
69  * Cleanup Dilatometer pointers
70  */
71 void Dilatometer_Cleanup()
72 {
73         if (g_capture != NULL)
74                 cvReleaseCapture(&g_capture);
75         if (frame != NULL)
76                 cvReleaseImageHeader(&frame);
77         //if (g_srcRGB != NULL)
78         //      cvReleaseMat(&g_srcRGB);        // Causing run time error in cvReleaseMat
79         if (g_srcGray != NULL)
80                 cvReleaseMat(&g_srcGray);
81         if (g_edges != NULL)
82                 cvReleaseMat(&g_edges);
83 }
84
85 /**
86  * Get an image from the Dilatometer
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 /**
123  * Applies the Canny threshold algorithm to the captured image.
124  */
125 void CannyThreshold()
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, kernel_size );
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 new location of the edge.
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_GetEdge( double * value, int samples)
163 {
164         bool result = false; 
165         double average = 0;
166         // Get the image from the camera
167         result = Dilatometer_GetImage();
168         // If an error occured when capturing image then return
169         if (!result)
170                 return result;
171         
172         // Apply the Canny Edge theorem to the image
173         CannyThreshold();
174
175         int width = g_edges->cols;
176         int height = g_edges->rows;
177         
178         // If the number of samples is greater than the image height, sample every row
179         if( samples > height)
180         {
181                 samples = height;
182         }
183         
184         int sample_height;
185         int num_edges = 0;      // Number of edges. if each sample location has an edge, then num_edges = samples
186
187         for (int i=0; i<samples; i++)
188         {
189                 // Determine the position in the rows to find the edges. 
190                 // This will give you a number of evenly spaced samples
191                 sample_height = ceil(height * (i + 1) / samples) -1;
192                 
193                 // 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).
194                 
195                 int edge_location=0;
196                 int num=0;
197                 for ( int col = 0; col < width; col++)
198                 {
199                         // Count the number of points
200                         // Get the threshold of the pixel at the current location
201                         CvScalar value = cvGet2D(g_edges, sample_height, col);
202                         if( value.val[0]> THRES)
203                         {
204                                 edge_location += col;
205                                 num++;
206                         }
207                 }
208                 if( num > 0)
209                 {
210                         average += ( edge_location / num );
211                         num_edges++;
212                 }
213         }
214         if (num_edges > 0)
215                 average /= num_edges;
216         
217         if( average > 0)
218         {       
219                 result = true; //Successfully found an edge
220                 *value = average;
221         }
222         return result;
223 }
224
225  /**
226  * Read the dilatometer image. The value changed will correspond to the new location of the edge.
227  * @param val - Will store the read value if successful
228  * @returns true on successful read
229  */
230 bool Dilatometer_Read( double * value)
231 {
232         bool result = Dilatometer_GetEdge(value, SAMPLES);
233         return result;
234 }
235
236 /**
237  * Initialise the dilatometer
238  */
239 void Dilatometer_Init()
240 {
241         // Make an initial reading (will allocate memory the first time only).
242         double val;
243         Dilatometer_GetEdge(&val, 1); 
244 }
245
246 /**
247  * Overlays a line over the given edge position
248  */
249 void Draw_Edge(double edge)
250 {
251         CvScalar value;
252         value.val[0]=244;
253         for( int i = 0; i < g_srcGray->rows; i++)
254         {
255                 cvSet2D(g_edges,i,edge,value);
256         }
257         cvShowImage("display", g_edges);
258         cvWaitKey(0);   
259         //cvSaveImage("test_edge_avg.jpg",g_edges,0);
260 }
261
262 /* // Test algorithm
263 static void Dilatometer_GetImageTest( )
264 {       
265         //Generates Test image
266         //Dilatometer_TestImage();
267         
268         //Load Test image
269         g_srcGray = cvLoadImageM ("testimage4.jpg",CV_LOAD_IMAGE_GRAYSCALE );
270 }*/
271
272 /**
273  * For testing purposes
274  */
275 int main(int argc, char ** argv)
276 {
277         //cvNamedWindow( "display", CV_WINDOW_AUTOSIZE );// Create a window for display.
278         //gettimeofday(&start, NULL);
279         test_left = 100;
280         test_right = 500;
281         Dilatometer_Init();
282         
283         cvNamedWindow( "display", CV_WINDOW_AUTOSIZE);
284         //double width;
285         
286         double edge;
287         Dilatometer_GetEdge(&edge,20000);
288         //For testing purposes, overlay the given average line over the image
289         //Draw_Edge(edge);
290         
291         cvDestroyWindow("display");
292
293         Dilatometer_Cleanup();
294 }
295

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