Friday, July 18, 2014

Building & Running CMU Sphinx4 for Speech Recognition on Ubuntu 12.04

Step-1: Download JDK7, Eclipse IDE and install them.

Step-2: Download Sphinx4 from here. Download both files sphinx4-1.0beta6-src.zip and  sphinx4-1.0beta6-bin.zip

step-3: Extract both files  sphinx4-1.0beta6-src.zip and sphinx4-1.0beta6-bin.zip  using unzip command.

step-4: After extracting execute the following commands
             cd /home/UserName/sphinx4-1.0beta6-bin/sphinx4-1.0beta6/lib/
             sudo chmod 777 jsapi.sh
             sudo bash jsapi.sh (Make sure all jar files extracted properly)

Step-5: Now create a new java project "HelloWorld" in eclipse.

Step-6: copy all files in the folder "sphinx4-1.0beta6-src/sphinx4-1.0beta6/src/apps/edu/cmu/sphinx/demo/helloworld/" in newly created project "HelloWorld".


Step-7: Include all jar files in the folder "sphinx4-1.0beta6-bin/sphinx4-1.0beta6/lib/" in the project's java build path in eclipse. To include jar files right click on HelloWorld Project then properties->Java build path->Libraries->Add External JARs-> select all jar files in "sphinx4-1.0beta6-bin/sphinx4-1.0beta6/lib/".

Including Sphnix4 Jar Files
 
Step-8: Now Run project and follow instructions displayed on console for speech recognition.

Sphnix4 Setup in Eclipse


Wednesday, February 26, 2014

Open House At CDAC Khargar On 28-02-2014


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;
}

Friday, October 18, 2013

UNIX Shared Memory Implementation

-Shared Memory Allows two unrelated processes to access the same memory.
-Shared memory is created by one process and appears to other processes by attach.
-If one process writes to shared memory, the changes immediately visible to any
other process that has access to shared memory.
-Shared Memory provides no synchronization.


Header files to include: <sys/types.h> ,<sys/ipc.h>, <sys/shm.h> <unistd.h>

Creating Shared Memory:
int shmget (key_t key, size_t size, int shmflg);
- Key: unique identification to memory
- Size: of shared memory
- Shmflg: IPC_CREAT | WR permissions, IPC_PRIVATE
- Returns:On Success: shmid On failure: -1


Attaching Shared Memory:
void * shmat(int shmid, void * shmaddr, int shmflg)
– Shmid: returned by shmget
– Shmaddr: shared memory segment address (normally NULL)
– Shmflg : SHM_RDONLY, SHM_RND
- Returns: on success: attached address, on failure: (void*)-1


Detaching Shared Memory:
int shmdt (void *shmaddr)
– Shmaddr: address returned by shmat
- Returns: on success: 0 on failure: -1


Removing Shared Memory:
Shmctl(int shm_id, int cmd, struct shmid_ds *buf)
- shm_id: returned by shmget
- cmd: command to control shared memory ex: for remove IPC_RMID
- Returns: on success:0 On failure:-1


/* Shared Memory implementation */


/* FileName: SMServer.c */

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE  100

int main()
{
    char c;
    int shmid;
    key_t key;
    char *shm, *s;

    key = 1234;

     // Creating shared memory  
     if ((shmid = shmget(key, MAXSIZE, IPC_CREAT | 0666)) < 0)
        {
           printf("Error in creating shared memory \n");
           exit(0);
        }
     else
         printf("Shared Memory Created with id %d\n", shmid);
    // Attaching shared memory to this process

    if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
        {
           printf("Error in attaching shared memory \n");
        }
     else
        printf("Shared memory attached \n");

    s = shm;

   // Writing data on shared memory
   printf("\nEnter a message to add to message queue: ");
   scanf("%[^\n]s",s);
   getchar();
   printf("Entered message now available on Shared memory \n");

   // Deleting shared memory
   //if(shmctl(shmid, IPC_RMID, 0)==0)
     //printf("Shared memory deleted\n");

    exit(0);
}

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




/* FileName: SMClient.c */


#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE  100

int main()
{
    int shmid;
    key_t key;
    char *shm, *s;

    key = 1234;

    if ((shmid = shmget(key, MAXSIZE, 0666)) < 0)
        {
           printf("Error in accessing shared memory \n");
           exit(0);
        }
        else
        {
           printf("Accessing shared memory od id %d\n", shmid);
        }

    if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
        {
           printf("Error in attaching shared memory\n");
        }
    else
        {
           printf("Shared Memory Attached \n");
        }

    //Now read what the server put in the memory.
    for (s = shm; *s != '\0'; s++)
        putchar(*s);
        putchar('\n');

   if(shmdt(shm)==0)
     {
         printf("Shared memory detached\n"); 
        
     }
    exit(0);
}

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


Mapping & Unmapping a XWindow

XMapWindow(Display*, Window) - is used to map(visible) a Xwindow on top of all window.

XUnmapWindow(Display*, Window) - is used to unmap(hime) a Xwindow.

/* CPP program to map & unmap a Xwindow */
/* FileName: MapUnMap.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;
    }

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



To Run: g++ MapUnMap.cpp -lX11

               ./a.out