Thursday, November 28, 2013

Importing a new font in Windows 7 and/or Android

For Android programming, see below the ***** line...
But as I was on this, I decided to check how to do it for Windows 7 :). These are the steps:
  1. Download the font file (extension ttf). There are several free sites. Check in case they are not completely free (donation, or shareware, or...). This is a site I used.
  2. For the next step, folks say to make sure that all your office programs (Outlook, Word, etc...) are closed.
  3. If the file is zip, unzip it (duh!), and then right click on the file and select Open with - Windows Font Viewer. You will see the fonts and on top, the Install button.
  4. Done! You should now be able to see them in your Font menus, in Office.
**********************************
For Android programming:
  1. Download the font file (extension ttf). There are several free sites. Check in case they are not completely free (donation, or shareware, or...). This is a site I used.
  2. If the file is zip, unzip it (duh!), and then place it in the assests directory of your project.
  3. Then use something like the following (basically extracted from this post in StackOverflow):
 protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);       
           mdisplay = (TextView) findViewById(R.id.textView1);  
           try{  
                Typeface myTypeface = Typeface.createFromAsset(this.getAssets(),"wwDigital.ttf");  
                mdisplay.setTypeface(myTypeface);  
           }  
           catch (IllegalStateException e){  
                System.out.println("This didn't work very well");  
                return;  
           }  
           mdisplay.setTextSize(50);  
           mdisplay.setTextColor(Color.RED);  
      }  

Good luck!

PS.: Please, click here to see an index of other posts on Android. 

Sunday, November 17, 2013

Open access to publicly funded research

I always wondered why one had to pay those hefty prices for online articles... One could think that it makes sense, in general, but why, even for the ones which research had been funded by tax payers. There are lots of arguments (quality, reviews...) but honestly, I think they are mostly excuses to justify a business that in the past, with no Internet, made more sense...

Anyhow, this became a real issue for me when I was trying to research about some physical symptoms, that eventually, fortunately, proved to be nothing serious. At the time, I signed a petition to the government to solve this... And happily enough, things seem to be coming together. It seems to be fair to give this point to Obama administration although I am sure there were many folks on both sides behind this. It would be interesting to research that, but life is too short :)

I leave you with a video from Jack Andraka, a kid and a scientist, explaining what I felt few years ago...

How much waste goes into defending wrong things... Folks don't realize that eventually everything flows to the right state.

Friday, November 8, 2013

OpenCV: How to get started and index of posts

So, you want to do some cool image processing... so, here is a very basic explanation on how to get started with link/index to the stuff I posted so far.

Where to start

Basically OpenCV is a set of nice libraries that will highly expedite a lot of your work. See more detail here. You will need to call them from your program, say in C/C++ or Java.

To develop the program you will need an IDE (integrated development environment) which takes care of editing (more than a text editor, with nice support features), and allows you to "plug in", compilers, debuggers, etc... so that you can run everything from there. In my case, I am using Eclipse. Notice that you could use a different IDE. During configuration of the IDE, you tell it what compiler to use, etc... So that when you press the compile button, Eclipse calls it to generate the object file... I think you get the point...

So, install Eclipse if you don't have it. Of course, you could choose a different IDE, but sorry, no experience on that, and honestly, I have no complains about Eclipse. Great tool. In my case, I did the installation when I was planning to use it with Qt (a set of widgets for something that I was doing completely unrelated). Still, the initial portion of the installation is the same. You can see my installation experience here.

So, what do I choose, C/C++ or Java?

Not an expert on this but I believe that a lot of the initial stuff on OpenCV was done for C development. Nevertheless, I think that almost everything in OpenCV has a port to Java already. I.e., there are packages in Java equivalent to libraries in C. So, probably depends more on what language you feel comfortable with.

One thing I was thinking (and I was wrong) is that if I want to use OpenCV in Android, I better get a handle of the Java version, as that is the language to develop in that platform (see this overview on Android programming environment). Nevertheless, that it's not that truth. In Android development, there is something called the NDK which allows you to call pieces of C code (native code) from the java code (see more info here on the NDK). The funny part is that in the end, as OpenCV is pretty processing intensive, you may want to use the NDK for the OpenCV routines (native code runs much faster than java code, if you do things properly...). Bottom line, I went down the path of working with OpenCV in Java, but probably I (and you, if you prefer) could have saved part of that work, as I was more familiar with C. But as I went down that path, I end-up with Eclipse supporting both languages (that is done with the "views"). So, to install each of the languages to work with OpenCV in a PC CPU, follow:
  1. Installation to work with C/C++
  2. Installation to work with Java
To develop for an Android machine, follow this.

Note: The 3 links above are in the order of what I historically did on my case. I.e., the 3 steps may not be completely independent of each other. For instance, something got installed in step 2 that is needed for Android, but I never realized and if I had done only the third, it would not have worked. Please let me know if you got any trouble...

Coding examples

So, now that you got it installed, let's do some coding:
  1. As part of the installation of OpenCV in Java (the same link as above) we did a first tutorial where we detect faces in an image file in a PC.
  2. Creating windows in Java and drawing in them. We strip everything to get familiar with the java drawing/workings. There is no OpenCV here. I read an image file from disk and display it. No detection yet.
  3. Next, we create windows and capture webcam, i.e., not from a file, like in #1. Although we do not do any image processing, we do use OpenCV structures to be ready for the next step (processing). 
  4. One of the keys on that post is how to take a Mat structure from OpenCV and pass it to BufferedImage, for display in Java. I created a post just for that.
  5. And into image processing, we now detect the faces on the webcam stream. Notice that this is very similar (a port to Java) of the original C tutorial
  6. Then we move into detecting a ball in the image. Part of the detection is based on color. So, you got to understand the color space. See this.
  7. And then we track the ball with the PC camera/CPU.
  8. Then we start moving into Android with a first app using OpenCV.
  9. Here we track faces with OpenCV in Android, using the smart phone camera. And here I use the Android SDK for the same thing.
  10. Using the face tracking I created a 3D display, which seems to be a similar technique to what Amazon is going to be using on their phone.
  11. And finally, we port the tracking of the ball to Android, i.e., we use the smart phone camera/CPU.
  12. The last final thing that I had in plan but haven't done yet is to actually port it to Android but have the OpenCV CPU intensive routines done in a C library, with the NDK.
For the next posts I am going to be concentrating in Android development, not related to OpenCV, but I'll be back :)

Cheers!!

Tuesday, November 5, 2013

Saving to a file in Android

We create the routine apart, as part of a task, but that is irrelevant to the topic. Straight to the code...
async_save_file.java
 package com.example.saveit;  
 import java.io.DataOutputStream;  
 import java.io.File;  
 import java.io.FileOutputStream;  
 import java.text.SimpleDateFormat;  
 import java.util.Date;  
 import java.util.Locale;  
 import android.content.Context;  
 import android.os.AsyncTask;  
 import android.os.Environment;  
 import android.os.Handler;  
 import android.os.Message;  
 import android.util.Log;  
 public class async_save_file extends AsyncTask<Void, Void, Void> {  
   Context mContext;  
   private Handler threadHandler;  
   private int[] audio_buffer;  
   public async_save_file(Context context,Handler threadHandler, int[] buffer) {  
     super();  
     this.threadHandler=threadHandler;  
     this.audio_buffer=buffer;  
     mContext = context;  
       }  
   @Override  
     protected Void doInBackground(Void...params) {   
     String root = Environment.getExternalStorageDirectory().toString();  
     File myDir = new File(root + "/captured_files");    
     if (myDir.exists()) Log.v(saveit.TAG,"S: Diretory exists!");  
     else {  
          myDir.mkdirs();   
          Log.v(saveit.TAG,"S: Diretory created!");  
     }  
     String dateInString = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss",Locale.US).format(  
         new Date()).toString();  
     String fileName = dateInString + "_record.bin";  
     File file = new File (myDir, fileName);  
     Log.v(saveit.TAG,"S: file path: "+file.getPath());  
     if (file.exists ()) file.delete ();   
     try {  
          FileOutputStream out = new FileOutputStream(file);  
       DataOutputStream out_s = new DataOutputStream(out);  
           Log.v(saveit.TAG, "L: Length: "+audio_buffer.length);  
           for (int i=0;i<audio_buffer.length;i++) out_s.writeChar(audio_buffer[i]);  
           //out_s.flush();  
           //out.flush();  
           //out.close();  
           out_s.close();   
              Message.obtain(this.threadHandler, saveit.ACK_SAVED, "SAVED").sendToTarget();   
                return null;  
       } catch (Exception e) {  
            e.printStackTrace();  
                    Message.obtain(this.threadHandler, saveit.ACK_NOT_SAVED, "FAILED SAVING").sendToTarget();   
                    return null;  
       }  
   }  
 }  
Notice also the flushing of the file (most of it commented out as the last instruction takes care of the rest). See flushing the file and Will closing a dataoutputstream close also the fileoutputstream. This is called from saveit.java
 package com.example.saveit;  
 import android.os.Bundle;  
 import android.os.Handler;  
 import android.annotation.SuppressLint;  
 import android.app.Activity;  
 import android.util.Log;  
 import android.view.View;  
 import android.widget.Button;  
 import android.widget.TextView;  
 import android.widget.Toast;  
 public class saveit extends Activity {  
      public static final int ACK_SAVED=1;  
      public static final int ACK_NOT_SAVED=2;  
      public static final String TAG = "MyActivity";  
      private TextView mResult;       
      private Button save_array;                    // To trigger the whole process  
      private int[] audio_buffer={1,2,3,4};  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.saveit_layout);  
           save_array=(Button)findViewById(R.id.button1);  
           mResult=(TextView)findViewById(R.id.display);  
           save_array.setOnClickListener(new View.OnClickListener() {  
                @Override  
                public void onClick(View v) {  
                     // TODO Auto-generated method stub  
                     new async_save_file(getApplicationContext(),threadHandler,audio_buffer).execute();  
                     Log.v(TAG, "UI: SAVING");  
                     mResult.setText("SAVING");        
                }  
           });  
      }  
      ////////////////////////////////////thread Handler///////////////////////////////////////  
      @SuppressLint("HandlerLeak")  
      private Handler threadHandler = new Handler() {  
           public void handleMessage(android.os.Message msg) {  
           switch(msg.what){  
                case ACK_SAVED:  
                     Toast.makeText(getBaseContext(), (String)msg.obj, Toast.LENGTH_SHORT).show();  
                     mResult.setText("SAVED");   
                     break;  
                case ACK_NOT_SAVED:  
                     Toast.makeText(getBaseContext(), (String)msg.obj, Toast.LENGTH_SHORT).show();  
                     mResult.setText("NOT SAVED");   
                     break;  
                }            
           }  
      };  
 }  
Along the way, I also used few ways to display results/debug notices... just as example...

The manifest:
 <?xml version="1.0" encoding="utf-8"?>  
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
   package="com.example.saveit"  
   android:versionCode="1"  
   android:versionName="1.0" >  
   <uses-sdk  
     android:minSdkVersion="9"  
     android:targetSdkVersion="17" />  
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
   <application  
     android:allowBackup="true"  
     android:icon="@drawable/ic_launcher"  
     android:label="@string/app_name"  
     android:theme="@style/AppTheme" >  
     <activity  
       android:name="com.example.saveit.saveit"  
       android:label="@string/app_name" >  
       <intent-filter>  
         <action android:name="android.intent.action.MAIN" />  
         <category android:name="android.intent.category.LAUNCHER" />  
       </intent-filter>  
     </activity>  
   </application>  
 </manifest>  
And the layout:
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:paddingBottom="@dimen/activity_vertical_margin"  
   android:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin"  
   tools:context=".MyAdderActivity" >  
   <Button  
     android:id="@+id/button1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_centerHorizontal="true"  
     android:layout_marginTop="81dp"  
     android:text="@string/save_button" />  
   <TextView  
     android:id="@+id/display"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_below="@+id/button1"  
     android:layout_centerHorizontal="true"  
     android:text="@string/display" />  
 </RelativeLayout>  
Cheers!

PS.: Please, click here to see an index of other posts on Android.