Archive | January, 2012

Integrate C code within Java code using Java Native Interface in Ubuntu

3 Jan

Java and C are two of the most widely used high level programming languages today. As a result of which there is often a need to incorporate the two in a single application. Like say for example, we have some legacy code written in C or C++ and we want to use certain features of the powerful Java platform within our application without rewriting the legacy code in Java.

This is where JNI or Java Native Interface comes riding in from the darkness on a fine steed and helps save the day.

This post serves to illustrate how to write a simple HelloWorld application using JNI wherein a certain function written in C will be invoked from a Java driver class.

And oh, this is for the Linux user. So if you are on Windows you should be better off Googling the same issue.

Prerequisites:

Needless to say, your system should have Java installed. I do not wish to digress and explain installing Java on Linux, there are a host of tutorials that will help you with the same.

So first up, we write a tiny Java code, and then analyse it’s anatomy to see how it’s different from the usual Java code.

import java.io.*;


class HelloWorld {
private native void nprint();
public static void main(String[] args) {
new HelloWorld().nprint();
}


static {
System.loadLibrary(“HelloWorld”);
}
}

It’s a simple HelloWorld class with a few striking features.

  1. private native void nprint(); This statement is crucial here. What it does is, it declares a native method, nprint(). (hence the n in the beginning) What is a native method? A native method is one that is implemented in some other native language (in this case, it will be, in C)
  2. public static void main(String[] args)  – the usual driver method. It invokes the aforementioned method nprint()
  3. System.loadLibrary(“HelloWorld”) locates a native library corresponding to the name “HelloWorld” and loads the native library into the application. It shall be clearer as we progress.
Now we compile this class. So head over to your terminal and type
javac HelloWorld
Now we need to create a native header file that we can include in our C program. Doing that is simple. Another line in the terminal:
javah jni HelloWorld
Now if you do an ls -al, you shall see the original HelloWorld.java file that you’ve written, the HelloWorld.class file that was produced after compilation and HelloWorld.h – the header file that just got created.
If you check the contents of the header file, you’ll see this line
JNIEXPORT void JNICALL Java_HelloWorld_nprint
  (JNIEnv *, jobject);
Java_HelloWorld_nprint(JNIEnv *, jobject) : This is the C method that we implement. All the fanciful names in the function name – forget them for the time being, and proceed with the task at hand.
Also, this is important. The header file is system generated. So DO NOT EDIT it. Right, with that caution in mind, we move to the remaining part.
Now we write the native code in C.
#include jni.h
#include stdio.h
#include “HelloWorld.h”
JNIEXPORT void JNICALL
Java_HelloWorld_nprint(JNIEnv *env, jobject obj) {
printf(“Hello JNI World!\n”);
return;
}
Do not blindly copy this code! Thanks to Blogger’s adeptness at parsing everything within angular brackets as html and not displaying the same I have been unable to include the header files in their proper syntax. Simply enclose jni.h and stdio.h within angular brackers and we’re done.
Also notice that the function that we’ve written is the same function whose prototype we saw in the header file. This function isn’t difficult to comprehend – save for the high sounding names, but let us leave that there.
Now we need to compile the C code and create a native library . We shall use our favourite compiler and all it takes is a single line in the terminal.
gcc -I/usr/lib/jvm/java-6-openjdk/include  -o libHelloWorld.so -shared HelloWorld.c
This command compiles HelloWorld.c and also creates a native library called libHelloWorld. You will find the newly created library file libHelloWorld.so within your current working folder.
Now we are all set to run our Java program. There is however one thing we need to take care of. We need to define the native library directory path. To do that we run the following two commands.
LD_LIBRARY_PATH=.
(This is because the native shared library is contained within the current folder ( . ) )
and then
export LD_LIBRARY_PATH
That is it. Now we are all set to run our first JNI program.
 java -Djava.library.path=. HelloWorld
If all goes well, you’ll see the output.
Hello JNI World!
There you go. Your first working JNI program!
To sum up, here’s a screenshot from my terminal, that shows the sequence of shell commands (click for bigger picture).

Hello world!

2 Jan

Welcome to WordPress.com. After you read this, you should delete and write your own post, with a new title above. Or hit Add New on the left (of the admin dashboard) to start a fresh post.

Here are some suggestions for your first post.

  1. You can find new ideas for what to blog about by reading the Daily Post.
  2. Add PressThis to your browser. It creates a new blog post for you about any interesting  page you read on the web.
  3. Make some changes to this page, and then hit preview on the right. You can always preview any post or edit it before you share it to the world.

Setting up OpenCV 2.3 and Eclipse on Ubuntu 11.10

1 Jan
This post seeks to help you in installing OpenCV and Eclipse and setting them up on Ubuntu 11.10 Oneiric so that you can begin development straight away.

What is OpenCV? OpenCV is a library of programming functions (in C and some C++ classes) mainly aimed at real time computer vision and image processing. It is a cross platform library, first developed by Intel and now supported by Willow Garage, and is free for use under the open source BSD license.

What is Eclipse? Eclipse is a multi-language software development platform comprising an IDE and lots of plug ins to help you develop applications in several widely used programming languages.

This walk through is aimed at helping you to set up OpenCV 2.3 (the latest version as of January 2012), and Eclipse CDT (Eclipse with the C Development Toolkit) on Ubuntu 11.10.

Ubuntu 11.10 does come with OpenCV 2.1 in the repositories, but we want OpenCV 2.3 … so we first begin with adding a PPA for OpenCV 2.3.

Head over to the terminal and type

$ sudo add-apt-repository ppa:gijzelaar/cuda
$ sudo add-apt-repository ppa:gijzelaar/opencv2.3
$ sudo apt-get update

Now, do the usual apt-get to get OpenCV. Note that the usual Ubuntu repos have a package called libcv-dev, however with the new PPA we are looking for a package called libopencv-dev.


$ sudo apt-get install libopencv-dev

This installs OpenCV on your computer. You will find the package files in /usr/include/opencv/

Now for Eclipse. You can do the usual apt-get (sudo apt-get install eclipse) to get Eclipse or you can download from the official website. I recommend the former. At the end you should have the following packages installed on your machine. ( I further recommend you install Synaptic Package Manager (sudo apt-get install synaptic) and then check for the individual packages.)


eclipse
eclipse-platform
eclipse-rcp
eclipse-platform-data
eclipse-pde
pdebuild
eclipse-cdt


Now you should be able to launch Eclipse. So do that and then create a new C or C++ project.


We shall write an introductory OpenCV program in C++ in this project, so we name the project ImageDisplay. (Note that I have created a C++ project and not a C project. While Ubuntu comes with the default gcc compiler for C, it does not have the GNU C++ compiler, g++ by default. In case you also wish to use C++ instead of C, do a sudo apt-get install g++ to install the g++ compiler on your computer).



We now have a C++ project called ImageDisplay. To enable us to use the OpenCV libraries in this project we need to include these libraries. To do that, right click on the ImageDisplay project in the Project Explorer on the left and select Properties. Go to C/C++ build in the left menu and then Settings, in the dialog box that appears.

The Configuration bar should be set to Debug [ Active ]. In the Tool Setting tab, select Directories in the GCC C++ Compiler menu and add the path

/usr/include/opencv


Now go to Libraries under GCC C++ Linker and add the libraries that you would need. Typically you would definitely need opencv_core and opencv_highgui. The other libraries that you can add are


opencv_imgproc
opencv_ml
opencv_video
opencv_features2d
opencv_calib3d
opencv_objdetect
opencv_contrib
opencv_legacy
opencv_flann


Lastly, in the Library search path, add /usr/lib.


Make sure that you add these paths and directories for the Release build as well (in the Configuration bar).


Now we are all set to write our first OpenCV program.


Before that let us once run through what all we’ve done.

  • Installed OpenCV.
  • Installed Eclipse.
  • Installed G++.
  • Created a project called ImageDisplay.
  • Configured the libraries and paths with our project.

Now for the program.


Create a file within your ImageDisplay project called main.cpp. Also, copy an image (.jpg format) to your project workspace folder. (You had set your workspace folder when you had started Eclipse. If you do not remember, then it mostly is in your home folder, and it’s called workspace. There’ll be a folder within the folder corresponding to you current project called ImageDisplay. So copy the image there. Call it image.jpg)


Double click main.cpp in the Project Explorer and write the following piece of code. If all goes well, when you compile and run this program, you should see a window and your image.jpg should be displayed in it.
Just replace the quotes in the include statements with angular brackets.


#include “cstdlib”
#include “cmath”
#include “cv.h”
#include “highgui.h”


int main(int argc, char *argv[])

{

cvNamedWindow( “Example1”, CV_WINDOW_AUTOSIZE );
IplImage* img = 0;
img=cvLoadImage(“image.jpg”);
cvShowImage(“Example1”, img );
cvWaitKey(0);
cvReleaseImage(&img );
return 0;
}

Now save this file (Ctrl+S) and compile the code (ie “build” the project with Ctrl+B). Now click on the green arrow in the Eclipse toolbar to run the code.


You should see a window pop up called Example1 and your image.jpg should be in it.

You might face an error during compile time / run time that looks something like this :

Gtk-WARNING **: Unable to locate theme engine in module_path: “pixmap”,

This is because you do not have a package in your system. To install it, just head over to the terminal and type

sudo apt-get install gtk2-engines-pixbuf

That should be it. If you face any problem reread this post again and follow it carefully. Else of course, you can drop me a mail.





Also a very Happy New Year. Why I don’t get all gaga on New Year’s can be summed up nicely in the words of Mark Twain.

New Year’s is a harmless annual institution, of no particular use to anybody save as a scapegoat for promiscuous drunks, and friendly calls, and humbug resolutions, and we wish you to enjoy it with a looseness suited to the greatness of the occasion

So there.