8 static CvCapture * g_capture = NULL;
9 static int g_captureID = -1;
11 void Image_Handler(FCGIContext * context, char * params)
14 int num = 0, width = 1600, height = 1200; // Set Default values
16 {"num", &num, FCGI_INT_T},
17 {"width", &width, FCGI_INT_T},
18 {"height", &height, FCGI_INT_T}
20 if (!FCGI_ParseRequest(context, params, val, 3)) // Populate val
22 // 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
23 else if (num < 0 || num > 1) {
24 FCGI_RejectJSON(context, "Invalid capture number");
26 // Ensure valid widths
27 } else if (width <= 0 || height <= 0) {
28 FCGI_RejectJSON(context, "Invalid width/height");
32 IplImage * src = NULL; // Source Image
33 CvMat * encoded = NULL; // Encoded Image
35 Camera_GetImage( num, width, height ,&src);
37 Log(LOGDEBUG, "About to encode");
38 encoded = cvEncodeImage(".jpg",src,0);
39 Log(LOGDEBUG, "Encoded");
41 Log(LOGNOTE, "Sending image!");
42 FCGI_PrintRaw("Content-type: image/jpg\r\n");
43 FCGI_PrintRaw("Cache-Control: no-cache, no-store, must-revalidate\r\n\r\n");
44 //FCGI_PrintRaw("Content-Length: %d", g_encoded->rows*g_encoded->cols);
45 FCGI_WriteBinary(encoded->data.ptr,1,encoded->rows*encoded->cols);
47 cvReleaseMat(&encoded);
48 cvReleaseImageHeader(&src);
52 * Attempts to get an image from a camera
53 * @param num - Camera id
54 * @param width - Width to force
55 * @param height - Height to force
56 * @param image - Pointer to CvMat* to set with result
57 * @returns true on success, false on error
59 bool Camera_GetImage(int num, int width, int height, IplImage ** frame)
61 Log(LOGDEBUG, "Called with arguments num=%d width=%d height=%d frame=%p", num,width,height, frame);
62 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // Need to use a mutex to ensure 2 captures are not open at once
63 pthread_mutex_lock(&mutex);
66 if( g_capture == NULL)
68 g_capture = cvCreateCameraCapture(num);
71 else if( num != g_captureID)
73 cvReleaseCapture(&g_capture);
74 g_capture = cvCreateCameraCapture(num);
78 if (g_capture != NULL)
81 cvSetCaptureProperty(g_capture, CV_CAP_PROP_FRAME_WIDTH, width);
82 cvSetCaptureProperty(g_capture, CV_CAP_PROP_FRAME_HEIGHT, height);
84 *frame = cvQueryFrame(g_capture);
85 result = (*frame != NULL);
87 //cvShowImage("display", *image);
89 //cvSaveImage("test.jpg",*image,0);
91 Log(LOGDEBUG, "At end of mutex");
94 pthread_mutex_unlock(&mutex); //Close the mutex
96 //NOTE: Never have a "return" statement before the mutex is unlocked; it causes deadlocks!
102 // Release the capture and IplImage pointers
103 //cvReleaseImageHeader(&g_frame);
104 cvReleaseCapture(&g_capture);