1 /*******************************************************************************
3 * rozkuk - OpenCV based corns camera recognition program
5 * Created for Eurobot 2010 competition.
7 * Petr Kubizňák (kubiznak.petr@gmail.com), 2010
9 ******************************************************************************/
15 #include <semaphore.h>
19 #include <opencv/cv.h>
20 #include <opencv/highgui.h>
22 #include "clr2float.h"
23 #include "masks_globals.h"
24 #include "t_decision_box.h"
27 #include <roboorte_robottype.h>
30 /******************************************************************************/
32 // uncomment next line to "log" the output frames - save them as pnm to the working directory
36 #define MODE_QUIT 0x01
37 #define MODE_REALTIME 0x02
38 #define MODE_RECOGNIZE 0x04
39 #define MODE_WAIT 0x08
41 // mask of all modes / errors
42 #define MASK_MODES 0x0F
43 #define MASK_ERRORS (~MASK_MODES)
46 #define ERR_MASK_READ_FAILURE 0x10
48 // default mode in standard session (i.e. on ppc)
49 #define START_MODE MODE_WAIT
51 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
53 // default mode in debug session (i.e. on pc)
55 #define START_MODE MODE_REALTIME
57 // highgui windows names
58 #define WINDOW_ORIG "ROZKUK original scene"
59 #define WINDOW_THRES "ROZKUK threshold"
60 #define WINDOW_MASK "ROZKUK mask"
61 #define WINDOW_PROD "ROZKUK product"
65 #define KEY_SPACE 0x20
75 // number of frames passed in rozkuk mode before refresh
78 #endif /*----------- DEBUG SESSION ONLY -----------*/
80 //default threshold and saturation
82 #define SATURATION 1.0
84 //mask filename pattern
85 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
86 #define MASKFILENAME "./mask%02d%c%c.pnm"
87 #else /******************** PPC *******************/
88 #define MASKFILENAME "./mask%02d%c%c.pnm"
89 #endif /*------------------------------------------*/
91 //size of frames from camera
92 #define FRAME_WIDTH 640
93 #define FRAME_HEIGHT 480
94 #define FRAME_SIZE (FRAME_WIDTH * FRAME_HEIGHT)
96 //both (side and center) subresults will be returned in one int masked binary as 00ccssss
97 #define MASK_SIDE 0x0F
98 #define MASK_CENTER_SHIFT 4
99 #define MASK_CENTER (0x03 << 4)
101 //number of results to select the most supported one from
102 #define DECISION_BOX_SIZE 5
104 //camera control system (if true, rozkuk recognizes, else it waits)
105 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
106 #define ORTE_CAMERA_CONTROL 1
107 #else /******************** PPC *******************/
108 #define ORTE_CAMERA_CONTROL orte.camera_control.on
109 #endif /*------------------------------------------*/
111 /******************************************************************************/
113 // function declarations
114 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
115 int saveFrame(const CvArr *img);
116 void drawPauseText(IplImage *img);
117 void displayProduct(const CvMat *floatMat, int sideConfig, int centerConfig);
118 void displayMasksSum(const CvMat *mat1, const CvMat *mat2, const char *windowName);
119 void displayFloatMat(const CvMat *floatMat, const char *windowName);
120 int modeRealtime(CvCapture* capture);
121 #endif /*----------- DEBUG SESSION ONLY -----------*/
122 int modeRecognize(CvCapture* capture, CORBA_octet currentColor);
123 int modeWait(CvCapture *capture);
124 int modeManager(int defaultMode);
125 int countThreshold(const IplImage *frame);
126 int recognize(const CvMat *frame, CvMat **masks, int masksCnt, double *resDist=NULL);
127 int loadMask(const char *filename, CvMat **mask);
128 int loadMasks(char color);
129 void freeMasks(void);
130 void rcv_cmr_ctrl_cb(const ORTERecvInfo *info, void *vinstance, void *recvCallBackParam);
132 /******************************************************************************/
134 // variable declarations
135 struct robottype_orte_data orte;
137 CvMat **sideMasks=NULL; //float mask matrices
138 CvMat **centerMasks=NULL;
139 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
140 CvFont font; //text font
141 #endif /*----------- DEBUG SESSION ONLY -----------*/
143 /******************************************************************************/
145 #if defined (ROZKUK_DEBUG) || defined (PPC_DEBUG) /************ BOTH DEBUG SESSIONS ************/
147 /** Saves current image to a new file in the current directory. */
148 int saveFrame(const CvArr *img) {
149 struct stat stFileInfo;
152 //find a non-existent filename
153 #if defined (ROZKUK_DEBUG)
154 char filename[30] = "snapshot00.png";
155 while(!stat(filename, &stFileInfo)) sprintf(filename, "snapshot%02d.png", ++i);
157 char filename[30] = "snapshot00.pnm";
158 while(!stat(filename, &stFileInfo)) sprintf(filename, "snapshot%02d.pnm", ++i);
161 fprintf(stdout, "Saving frame to %s...\n", filename);
163 return cvSaveImage(filename, img);
166 #endif /*----------- BOTH DEBUG SESSIONS -----------*/
168 /******************************************************************************/
170 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
172 /** Writes text "pause" in the CAMERA window. */
173 void drawPauseText(IplImage *img) {
174 cvPutText(img,"pause", cvPoint(300,440), &font, cvScalar(255,255,255));
175 cvShowImage(WINDOW_ORIG, img);
178 /******************************************************************************/
180 /** Displays in separate window the result of multiplying camera frame (in float)
181 * and recognized mask.
182 * @param floatMat Pointer to the camera frame converted to float matrix.
183 * @param sideConfig Index of recognized side situation.
184 * @param centerConfig Index of recognized center situation. */
185 void displayProduct(const CvMat *floatMat, int sideConfig, int centerConfig) {
186 CvMat *sideProduct = cvCloneMat(floatMat);
187 CvMat *centerProduct = cvCloneMat(floatMat);
189 cvMul(floatMat, sideMasks[sideConfig], sideProduct); //count product of frame and side mask
190 cvMul(floatMat, centerMasks[centerConfig], centerProduct); //count product of frame and center mask
191 displayMasksSum(sideProduct, centerProduct, WINDOW_PROD); //display sum
193 cvReleaseMat(&sideProduct);
194 cvReleaseMat(¢erProduct);
197 /******************************************************************************/
199 /** Displays a sum of two matrices in specified window. */
200 void displayMasksSum(const CvMat *mat1, const CvMat *mat2, const char *windowName) {
201 CvMat *sum = cvCloneMat(mat1);
203 cvAdd(mat1, mat2, sum);
204 displayFloatMat(sum, windowName);
209 /******************************************************************************/
211 /** Normalizes the matrix values and displays them in window specified by name.
212 * @param floatMat Pointer to matrix data to display.
213 * @param windowName Name of window in which to display the image. */
214 void displayFloatMat(const CvMat *floatMat, const char *windowName) {
215 double min=0.0, max=0.0;
216 CvMat *normalized = cvCloneMat(floatMat);
218 cvMinMaxLoc(floatMat, &min, &max); // find extremes
219 cvConvertScale(floatMat, normalized, 1/(max-min), -(min/(max-min))); // normalize
220 cvShowImage(windowName, normalized);
222 cvReleaseMat(&normalized);
225 /******************************************************************************/
227 /** Displays a real video in a window (only for DEBUG session).
228 * @param capture Pointer to a camera capture.
229 * @return Code of mode to switch to. */
230 int modeRealtime(CvCapture* capture) {
231 IplImage* frame = NULL; // frame from camera
232 int pause=0; // set pause=1 to pause the video
235 /* keyboard events handeling */
236 switch(cvWaitKey(10) & 0xFF) { // wait 10ms for an event
240 // switch to recognize mode
243 return MODE_RECOGNIZE;
248 drawPauseText(frame);
250 // save frame to file
257 frame = cvQueryFrame(capture); // Get one frame
259 fprintf(stderr, "NULL frame\n");
263 if(!pause) cvShowImage(WINDOW_ORIG, frame); // show image (! Do not release the frame !)
267 #endif /*----------- DEBUG SESSION ONLY -----------*/
269 /******************************************************************************/
271 /** Implements the camera recognition of corns.
272 * In DEBUG session the results are also displayed on screen.
273 * @param capture Pointer to a camera capture.
274 * @param currentColor Number of starting color. If it changes in orte during
275 * recognition, this mode needs to restart (to load suitable masks).
276 * @return Code of mode to switch to. */
277 int modeRecognize(CvCapture* capture, CORBA_octet currentColor) {
278 IplImage *frame = NULL; // frame from camera
279 IplImage *thresFrame = NULL; // thresholded frame
280 CvMat *floatMat = NULL; // float <-1,1> image of the frame
281 int sideConfig, centerConfig; // indices of recognized configurations
282 double sideDist, centerDist; // distances between the best and second best results
283 TDecisionBox sideBox(DECISION_BOX_SIZE, SIDEMASKSCNT); // side solutions "averaging" decision box
284 TDecisionBox centerBox(DECISION_BOX_SIZE, CENTERMASKSCNT); // center solutions "averaging" decision box
285 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
286 int framesPassed = PASS_FRAMES; // number of passed frames before refresh
287 int pause=0; // set pause=1 to pause processing
288 #endif /*----------- DEBUG SESSION ONLY -----------*/
289 while(ORTE_CAMERA_CONTROL) {
291 //if color changed during recognition, restart the mode to load appropriate masks
292 if(orte.camera_control.game_color != currentColor) return MODE_RECOGNIZE;
294 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
295 /* keyboard events handeling */
296 switch(cvWaitKey(10) & 0xFF) { // wait 10ms for an event
302 framesPassed = PASS_FRAMES;
304 // switch to recognize mode
307 return MODE_REALTIME;
312 drawPauseText(frame);
314 // save frame to file
324 #endif /*----------- DEBUG SESSION ONLY -----------*/
327 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
328 if(pause) cvQueryFrame(capture);
330 #endif /*----------- DEBUG SESSION ONLY -----------*/
331 frame = cvQueryFrame(capture);
333 fprintf(stderr, "NULL frame\n");
334 // save error code to orte and publish it
335 orte.camera_result.error |= camera_ERR_NO_FRAME;
336 ORTEPublicationSend(orte.publication_camera_result);
339 } else if(orte.camera_result.error & camera_ERR_NO_FRAME) {
340 orte.camera_result.error &= ~camera_ERR_NO_FRAME;
341 ORTEPublicationSend(orte.publication_camera_result);
344 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
347 // transform colorful image to its float <-1,1> representation
348 cvReleaseImage(&thresFrame);
349 thresFrame = cvCreateImage(cvSize(FRAME_WIDTH,FRAME_HEIGHT),IPL_DEPTH_8U,1);
350 #endif /*----------- DEBUG SESSION ONLY -----------*/
352 int threshold = countThreshold(frame);
353 clr2float(frame, &floatMat, threshold, SATURATION, thresFrame); // get float representation (in DEBUG session, thresholded image is stored to thresFrame)
354 //recognize side and center configurations
355 sideConfig = recognize(floatMat, sideMasks, SIDEMASKSCNT, &sideDist);
356 centerConfig = recognize(floatMat, centerMasks, CENTERMASKSCNT, ¢erDist);
357 fprintf(stderr, "SINGLE: thr: %3d, side: %d (%.2f), center: %d (%.2f)\n", threshold, sideConfig, sideDist, centerConfig, centerDist);
358 //push the results to the decision box and get "averaged" solutions from it
359 sideBox.insertItem(sideConfig, sideDist);
360 centerBox.insertItem(centerConfig, centerDist);
361 sideBox.decide(&sideConfig, &sideDist);
362 centerBox.decide(¢erConfig, ¢erDist);
364 orte.camera_result.side = sideConfig;
365 orte.camera_result.center = centerConfig;
366 orte.camera_result.sideDist = sideDist;
367 orte.camera_result.centerDist = centerDist;
368 ORTEPublicationSend(orte.publication_camera_result);
369 fprintf(stderr, "ORTE: side: %d (%.2f), center: %d (%.2f)\n", sideConfig, sideDist, centerConfig, centerDist);
371 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
372 displayProduct(floatMat, sideConfig, centerConfig);
373 #elif defined (PPC_DEBUG) ///////////// PPC DEBUG SESSION //////////////
375 #endif /*----------- DEBUG SESSION ONLY -----------*/
376 cvReleaseMat(&floatMat);
378 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
379 if(framesPassed++ > PASS_FRAMES) {
381 cvShowImage(WINDOW_ORIG, frame); // show image (! Do not release the frame !)
382 cvShowImage(WINDOW_THRES, thresFrame);
383 displayMasksSum(sideMasks[sideConfig], centerMasks[centerConfig], WINDOW_MASK); // display selected mask
384 cvReleaseImage(&thresFrame);
386 #endif /*----------- DEBUG SESSION ONLY -----------*/
392 /******************************************************************************/
394 /** Waits while no action is wanted. To stop waiting set orte.camera_control.on=TRUE
395 * or in DEBUG session press W key.
396 * @param capture Pointer to a camera capture.
397 * @return Code of mode to switch to. */
398 int modeWait(CvCapture *capture) {
399 while(!ORTE_CAMERA_CONTROL) {
400 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
401 //process keyboard events
402 switch(cvWaitKey(10) & 0xFF) { // wait 10ms for an event
410 return MODE_RECOGNIZE;
413 #endif /*----------- DEBUG SESSION ONLY -----------*/
414 fprintf(stderr, "waiting...\n");
417 return MODE_RECOGNIZE;
420 /******************************************************************************/
422 /** Switches between modes of the program.
423 * @param defaultMode The first mode to run. */
424 int modeManager(int defaultMode) {
425 int mode=defaultMode;
430 // connect to a camera
431 while(!((capture=cvCaptureFromCAM(0)) || (capture=cvCaptureFromCAM(1)))) {
432 fprintf(stderr, "NULL capture (is camera connected?)\n");
433 orte.camera_result.error |= camera_ERR_NO_VIDEO;
434 ORTEPublicationSend(orte.publication_camera_result);
437 orte.camera_result.error &= ~camera_ERR_NO_VIDEO;
438 ORTEPublicationSend(orte.publication_camera_result);
439 fprintf(stderr, "rozkuk started, camera connected successfully\n");
441 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
442 // create gui windows and init font
443 cvNamedWindow(WINDOW_ORIG, CV_WINDOW_AUTOSIZE); // real camera video / one frame viewer
444 cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 1.0, 1.0, 0, 1); //init text font
445 #endif /*----------- DEBUG SESSION ONLY -----------*/
447 while(!(mode & MODE_QUIT)) {
448 switch(mode & MASK_MODES) {
450 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
452 cvDestroyWindow(WINDOW_THRES);
453 mode = modeRealtime(capture);
455 #endif /*----------- DEBUG SESSION ONLY -----------*/
458 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
459 cvNamedWindow(WINDOW_THRES, CV_WINDOW_AUTOSIZE);
460 cvMoveWindow(WINDOW_THRES, cvQueryFrame(capture)->width, 0);
461 cvNamedWindow(WINDOW_MASK, CV_WINDOW_AUTOSIZE);
462 cvMoveWindow(WINDOW_MASK, 0, cvQueryFrame(capture)->height+50);
463 cvNamedWindow(WINDOW_PROD, CV_WINDOW_AUTOSIZE);
464 cvMoveWindow(WINDOW_PROD, cvQueryFrame(capture)->width, cvQueryFrame(capture)->height+50);
465 #endif /*----------- DEBUG SESSION ONLY -----------*/
466 //load masks and run recognition mode, then free masks (they are in memory only while in recognition mode)
467 color = orte.camera_control.game_color;
468 if((ret=loadMasks((color==BLUE ? clBLUE : clYELLOW)))) return ret;
469 mode = modeRecognize(capture, color);
474 mode = modeWait(capture);
478 goto end; // jump out of the loop
483 cvReleaseCapture(&capture);
484 #ifdef ROZKUK_DEBUG /************ DEBUG SESSION ONLY ************/
485 cvDestroyWindow(WINDOW_ORIG);
486 cvDestroyWindow(WINDOW_THRES);
487 cvDestroyWindow(WINDOW_MASK);
488 cvDestroyWindow(WINDOW_PROD);
489 #endif /*----------- DEBUG SESSION ONLY -----------*/
490 return mode & MASK_ERRORS;
493 /******************************************************************************/
495 /** Returns a threshold computed from the frame. */
496 int countThreshold(const IplImage *frame) {
497 return cvAvg(frame).val[0];
500 /******************************************************************************/
502 /** Returns an ordinary number of recognized layout.
503 * @param frame Float representation of frame.
504 * @param masks Array of masks to compare with.
505 * @param masksCnt Size of the array.
506 * @param resDist If not NULL, a distance between the best and second best result is stored here.*/
507 int recognize(const CvMat *frame, CvMat **masks, int masksCnt, double *resDist) {
508 double max = cvDotProduct(frame, masks[0]);
509 double max2 = -(FRAME_SIZE); // the least possible value
511 for(int i=1; i<masksCnt; i++) {
512 double prod = cvDotProduct(frame, masks[i]);
517 } else if(prod > max2) max2 = prod;
519 if(resDist) *resDist = max-max2;
523 /******************************************************************************/
525 /** Loads binary (float) data to *mask from file.
526 * @param filename Path to file to read.
527 * @param mask Address of array, where to alloc memory and store the data.
528 * @return Length of read data or zero in case of error. */
529 int loadMask(const char *filename, CvMat **mask) {
532 IplImage *img = cvLoadImage(filename, CV_LOAD_IMAGE_GRAYSCALE);
534 fprintf(stderr, "Mask %s cannot be loaded.\n", filename);
535 fprintf(stderr, "Run me from _build/user/camera/rozkuk\n");
540 if(!(len=clr2float(img, mask, CL_NEUTRAL, 1.0, NULL)))
541 fprintf(stderr, "A problem while converting mask to float occured.\n");
543 fprintf(stderr, "Mask %s successfully loaded.\n", filename);
545 cvReleaseImage(&img);
549 /******************************************************************************/
551 /** Loads all the float masks from files.
552 * @return Zero if ok, else non-zero. */
553 int loadMasks(char color) {
555 //alloc memory for arrays of masks
556 sideMasks = (CvMat **)malloc(SIDEMASKSCNT*sizeof(CvMat *));
557 centerMasks = (CvMat **)malloc(CENTERMASKSCNT*sizeof(CvMat *));
559 for(int i=0; i<SIDEMASKSCNT; i++) {
560 sprintf(filename, MASKFILENAME, i, orSIDE, color);
561 if(!loadMask(filename, sideMasks+i)) return ERR_MASK_READ_FAILURE;
563 for(int i=0; i<CENTERMASKSCNT; i++) {
564 sprintf(filename, MASKFILENAME, i, orCENTER, color);
565 if(!loadMask(filename, centerMasks+i)) return ERR_MASK_READ_FAILURE;
570 /******************************************************************************/
572 /** Frees the memory alloced for masks. */
573 void freeMasks(void) {
574 for(int i=0; i<SIDEMASKSCNT; i++) cvReleaseMat(sideMasks+i);
575 for(int i=0; i<CENTERMASKSCNT; i++) cvReleaseMat(centerMasks+i);
580 /******************************************************************************/
582 /** Orte camera control callback function. */
583 void rcv_cmr_ctrl_cb(const ORTERecvInfo *info, void *vinstance, void *recvCallBackParam) {
585 struct robottype_orte_data *orte_data = (struct robottype_orte_data *)recvCallBackParam;
586 #endif /*----------- ORTE_DEBUG -----------*/
588 switch (info->status) {
590 // nothing to do - changes will be processed in the recognition loop
592 printf("orte: New data: ctrl %d, clr %d\n", orte_data->camera_control.on, orte_data->camera_control.game_color);
593 #endif /*----------- ORTE_DEBUG -----------*/
596 printf("ORTE deadline occurred - CMR_CTRL receive\n");
601 /******************************************************************************/
603 int main(int argc, char *argv[]) {
606 ret = robottype_roboorte_init(&orte);
608 fprintf(stderr, "robottype_roboorte_init failed\n");
611 robottype_publisher_camera_result_create(&orte, NULL, NULL);
612 robottype_subscriber_camera_control_create(&orte, rcv_cmr_ctrl_cb, &orte);
614 modeManager(START_MODE);
616 ret = robottype_roboorte_destroy(&orte);