Done a bunch of changes to image handling
[matches/MCTX3420.git] / server / image.c
1 #include "cv.h"
2 #include "highgui_c.h"
3 #include "image.h"
4 #include <string.h>
5 #include <stdio.h>
6 #include <pthread.h>
7
8 CvCapture *capture;
9 int captureID = -1;
10
11 void Image_Handler(FCGIContext * context, char * params)
12 {
13         int num = 0, width = 1600, height = 1200;       // Set Default values
14         FCGIValue val[] = {
15                 {"num", &num, FCGI_INT_T},
16                 {"width", &width, FCGI_INT_T},
17                 {"height", &height, FCGI_INT_T}
18         };
19         if (!FCGI_ParseRequest(context, params, val, 3))        // Populate val
20                 return;
21         // Ensure the camera id is 0 or 1. Even though we plan to only have 1 camera attached at a time, this will allow 2. increase
22         else if (num < 0 || num > 1) {                          
23                 FCGI_RejectJSON(context, "Invalid capture number");
24                 return;
25         // Ensure valid widths
26         } else if (width <= 0 || height <= 0) {
27                 FCGI_RejectJSON(context, "Invalid width/height");
28                 return;
29         }
30         
31         CvMat * g_src = NULL;   // Source Image
32         CvMat * g_encoded;      // Encoded Image
33
34         Camera_GetImage( num, width, height ,g_src); 
35         g_encoded = cvEncodeImage("test_encode.jpg",g_src,0);
36
37         Log(LOGNOTE, "Sending image!");
38         FCGI_PrintRaw("Content-type: image/jpg\r\n");
39         FCGI_PrintRaw("Cache-Control: no-cache, no-store, must-revalidate\r\n\r\n");
40         //FCGI_PrintRaw("Content-Length: %d", g_encoded->rows*g_encoded->cols);
41         FCGI_WriteBinary(g_encoded->data.ptr,1,g_encoded->rows*g_encoded->cols);
42         
43         cvReleaseMat(&g_encoded);
44         cvReleaseMat(&g_src);
45 }
46
47  bool Camera_GetImage(int num, int width, int height,  CvMat * image)
48  {
49         static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // Need to use a mutex to ensure 2 captures are not open at once
50         pthread_mutex_lock(&mutex);
51         bool result = false;
52
53         capture = cvCreateCameraCapture(num);
54
55         cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
56         cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
57
58         IplImage * frame = cvQueryFrame(capture);
59         if( frame == NULL)
60                 return result;
61
62         // Convert the IplImage pointer to CvMat
63         CvMat stub;
64         image = cvGetMat(frame, &stub, 0, 0);
65         if( image == NULL)
66                 return result;
67
68         // Release the capture and IplImage pointers
69         cvReleaseImageHeader(&frame);
70         cvReleaseCapture(&capture);
71
72         pthread_mutex_unlock(&mutex);   //Close the mutex
73         return true;
74 }
75

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