Tuesday, December 31, 2013

A Broken Loop C puzzle

Question:

Find three ways to make the following program to print 20 times - (dash) by changing / adding just one character.

int i, n=20;
for(i=0; i < n; i--)
printf("-");


Answers:

/* FileName: printdash.c */

#include <stdio.h>
void main()
{
  int i, n=20;

  for(i=0; i+n; i--)
  printf("- ");
  printf("\n");

  for(i=0; -i < n; i--)
  printf("- ");
  printf("\n");

  for(i=0; i < n; n--)
  printf("- ");
  printf("\n");

}

To Run: gcc printdash.c
               ./a.out



Monday, December 30, 2013

Mapping - UnMapping A XWindow

                Because of race condition lot of people face problems in Mapping or UnMapping  a particular Xwindow and all of its sub-windows that have had map / unmap requests in X11R6. In this post I am going to show you how to Map and UnMap a Xwindow based on MapNotify and UnmapNotify events.



 /* FileName: Map_UnMap.cpp */

#include <X11/Xlib.h>
#include <assert.h> 
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#define NIL (0)

int main()
{

      Display *dpy = XOpenDisplay(NIL);
      assert(dpy);

      int blackColor = BlackPixel(dpy, DefaultScreen(dpy));
      int whiteColor = WhitePixel(dpy, DefaultScreen(dpy));


      Window w = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0,
                     200, 100, 0, blackColor, blackColor);

      XSelectInput(dpy, w, StructureNotifyMask);

      XMapWindow(dpy, w);
      sleep(2);
      printf( "Mapping : : 0x%x\n", (unsigned int)w);
      int count=1;
           
      GC gc = XCreateGC(dpy, w, 0, NIL);
      XSetForeground(dpy, gc, whiteColor);

      XEvent event;

      while ( 1 ) {
        XNextEvent( dpy, &event );
        if ( event.type == MapNotify ) {
            XMapEvent *mapevent = (XMapEvent *)&event;
            printf( "UnMapping    : 0x%x\n", (unsigned int)(mapevent->window) );
            ++count;
            XUnmapWindow(dpy, w);
            sleep(2);
        }

    if ( event.type == UnmapNotify ) {
            XUnmapEvent *unmapwindowevent = (XUnmapEvent *)&event;
            printf( "Mapping : 0x%x\n", (unsigned int)(unmapwindowevent->window) );
            ++count;
            XMapWindow(dpy, w);
            sleep(2);
        }
           if(count==10)
              break;

        if ( event.type == DestroyNotify ) {
            XDestroyWindowEvent *destroywindowevent = (XDestroyWindowEvent *)&event;
            printf( "Destroyed : 0x%x\n", (unsigned int)(destroywindowevent->window) );
        }
    }

      XFlush(dpy);
      sleep(3);
      return 0;
}

To Run: g++ Map_UnMap.cpp -lX11
             ./a.out

Programming A Webcam Recorder using OpenCV

There are 4 important steps in capturing video / images from webcam programmatically.
  1. Initialize webcam
  2. Capture frames from webcam for a particular duration
  3. Stop capturing frames from Webcam
  4. Release resources for escaping from memory leaks
Above mentioned 4 functionalities are implemented in the following class

/* File Name: WCRecorder.hpp */

#include <stdio.h>
#include <math.h>
#include <iostream>
#include <opencv/cv.h>
#include <opencv/highgui.h>
static int argc;
static char **argv;

class WebcamVideoRecorder
{
 public:
 CvCapture *capture;
 IplImage* rgb_image;
 bool initialized;
public:
 WebcamVideoRecorder(); /* constructor of  WebcamVideoRecorder calss */
 void Initialize(); /* Function to initialize webcam */
 void ProcessFrame(); /* Function to Capture frames from webcam */
 void StopProcessFrame(); /* Function to unCapture frames from webcam */
 void ReleaseResources(); /* function to release all resources */
};

/* File Name: WCRecorder.cpp */

#include <stdio.h>
#include <math.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include "WCRecorder_GUI.hpp"
/* Pre-requisite OpenCV-2.1.0 http://sourceforge.net/projects/opencvlibrary/files/opencv-unix/2.1/ */
/* Command to Run: g++ WCRecorder.cpp `pkg-config --cflags --libs opencv` */
using namespace std;

WebcamVideoRecorder::WebcamVideoRecorder() {
    capture = 0;
    rgb_image = 0;
    initialized = false;
}

void WebcamVideoRecorder::Initialize() {
    printf("OpenCV version %s (%d.%d.%d)\n", CV_VERSION, CV_MAJOR_VERSION,
            CV_MINOR_VERSION, CV_SUBMINOR_VERSION);
    capture = cvCaptureFromCAM(0);
    if (!capture) {
        fprintf(stderr, "Error in Capture...!!!\n");
        initialized = false;
    } else {
        cvNamedWindow("WebCam-Video-Recorder", 0);
        initialized = true;
    }
}

void WebcamVideoRecorder::ProcessFrame() {
    if (initialized) {
        string p_path(pfile_path);
        string p0_path(pfile_path);
        char str[10];
        CvVideoWriter *writer;
        IplImage *bgr_frame = cvQueryFrame(capture);
        CvSize size = cvGetSize(bgr_frame);
        rgb_image = cvCreateImage(cvGetSize(bgr_frame), bgr_frame->depth,
                bgr_frame->nChannels);
        if (vflag || pflag) {
            strcat((char*) vfile_path, ".avi");
            if (vflag)
                writer = cvCreateVideoWriter(vfile_path,
                        CV_FOURCC('I', 'Y', 'U', 'V'), 10.0, size);
            while (((bgr_frame = cvQueryFrame(capture)) != NULL)) {
                if (vflag)
                    cvWriteFrame(writer, bgr_frame);
                if (!bgr_frame)
                    break;
                cvCopy(bgr_frame, rgb_image);
                cvShowImage("WebCam-Video-Recorder", rgb_image);
                if (pflag) {
                    sprintf(str, "%d", ++nFrame);
                    p_path.append(str);
                    p_path.append(".jpeg");
                    cvSaveImage(p_path.c_str(), rgb_image);
                    p_path = p0_path;
                }
                char c = cvWaitKey(10);
                if (c == 27)
                    break;
            }
            cvReleaseVideoWriter(&writer);
        }
    }
    ReleaseResources();
}

void WebcamVideoRecorder::StopProcessFrame() {
    cvReleaseCapture (&capture);
}

void WebcamVideoRecorder::ReleaseResources() {
    cvReleaseImage (&rgb_image);
    cvReleaseCapture (&capture);
    cvDestroyWindow("WebCam-Video-Recorder");
}

int main(int argc_, char **argv_) {
    argc = argc_;
    argv = argv_;
    WebcamVideoRecorder WVR;
    WVR.Initialize();
    for(int i=0 ; i < 200 ; i++) /* here you can use timer to record that much of time */
    WVR.ProcessFrame();

    WVR.StopProcessFrame();
    WVR.ReleaseResources();
    return 0;
}