Object tracking in Java - detect position of colored spot in image

Red spot in image - position to be detected later
Object Tracking plays important role in Image Processing research projects. In this example, I am showing how we can detect the position [(x, y) coordinates ] of a colored spot in given image using JavaCV (Java wrapper for OpenCV ).



Input image :
This image has a red colored spot. And our objective is to track the position coordinate of the spot in image.The example below uses thresholding in HSV space and simple moment calculations given in OpenCV library.





You can use this code to track an object in a video sequence - say live web-cam capture video.


Detecting Position of a spot in Threshold image:
    static Dimension getCoordinates(IplImage thresholdImage) {
        int posX = 0;
        int posY = 0;

JavaCV: Image Thresholding HSV color space

JavaCV (OpenCv) example of image thresholding based on color in HSV-A Space - to detect red color spot on given image. Useful in object tracking.

Java Source Code:

//imports
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_highgui.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
import com.googlecode.javacv.cpp.opencv_core.CvScalar;
import com.googlecode.javacv.cpp.opencv_core.IplImage;

public class ColorDetect {

Java Sound : audio inputstream from pcm amplitude array

In this post, i am going to show the code for creating the AudioInputStream from an PCM - amplitude array. It basically converts the int [] array to byte array according to AudioFormat.

The code for the reverse operation (extract amplitude array from recorded wave file or AudioStream )is in my earlier post : http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/java-extract-amplitude-array-from.html

The code for converting PCM amplitude array to AudioStream is follows :

Java Sound : generate play sine wave - source code

Working source code example on how to generate and play sine wave in Java :
View my previous post  for playing any PCM amplitude array.

Generate Sine wave of a particular frequency :
    private static byte[] generateSineWavefreq(int frequencyOfSignal, int seconds) {
        // total samples = (duration in second) * (samples per second)
        byte[] sin = new byte[seconds * sampleRate];
        double samplingInterval = (double) (sampleRate / frequencyOfSignal);
        System.out.println("Sampling Frequency  : "+sampleRate);
        System.out.println("Frequency of Signal : "+frequencyOfSignal);
        System.out.println("Sampling Interval   : "+samplingInterval);
        for (int i = 0; i < sin.length; i++) {
            double angle = (2.0 * Math.PI * i) / samplingInterval;
            sin[i] = (byte) (Math.sin(angle) * 127);
            System.out.println("" + sin[i]);
        }

Java Audio : Playing PCM amplitude Array

How to play a array of PCM amplitude values (integer or float array) in Java - Steps

Basic Steps :
//initialize source data line - for playback
SourceDataLine line = AudioSystem.getSourceDataLine(audioFormat);
line.open(audioFormat);
line.start();

//play the byteArray
line.write(byteArray, 0,  byteArray .length);//(byte[] b, int off, int len)
line.drain();
line.close();

Converting integer array to bytearray :
We need to convert our PCM array to byteArray because the line.write requires byte[] b as parameter.

Java extract amplitude array from recorded wave

Extract amplitude array from recorded/saved wav : From File , AudioInputStream , ByteArray of File or ByteArrayInputStream - working java source code example

 import java.io.ByteArrayInputStream;  
 import java.io.File;  

Sound (audio file) player in java - working source code example

Sound (audio file) player in java - working source code example

 import java.io.File;  
 import java.io.IOException;  
 import javax.sound.sampled.AudioFormat;  
 import javax.sound.sampled.AudioInputStream;  
 import javax.sound.sampled.AudioSystem;  
 import javax.sound.sampled.DataLine;  

Java Sound Capture from Microphone working code

Sound  Capture / Record from Microphone and Save : working java source code example
 import java.io.ByteArrayInputStream;  
 import java.io.ByteArrayOutputStream;  
 import java.io.IOException;  
 import javax.sound.sampled.AudioFormat;  
 import javax.sound.sampled.AudioInputStream;  
 import javax.sound.sampled.AudioSystem;  
 import javax.sound.sampled.DataLine;  
 import javax.sound.sampled.TargetDataLine;  
 /**  
  * Reads data from the input channel and writes to the output stream  
  */  
 public class MicrophoneRecorder implements Runnable {  
   // record microphone && generate stream/byte array  
   private AudioInputStream audioInputStream;  

Java Reflection - Getting name of color without comparision

In this tutorial I am describing how get value of field/ property defined in class dynamically using Java Reflection.
And i am using it to get name of color (java.awt.Color) using Reflection.

Instead of doing lengthy comparison (shown below), we can do this easily by using java reflection:
   public static String getNameReflection(Color colorParam) {
        try {
            //first read all fields in array
            Field[] field = Class.forName("java.awt.Color").getDeclaredFields();
            for (Field f : field) {
                String colorName = f.getName();
                Class<?> t = f.getType();
                // System.out.println(f.getType());
                // check only for constants - "public static final Color"
                if (t == java.awt.Color.class) {
                    Color defined = (Color) f.get(null);
                    if (defined.equals(colorParam)) {
                        System.out.println(colorName);
                        return colorName.toUpperCase();
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("Error... " + e.toString());
        }
        return "NO_MATCH";
    }

Getting name of color by Comparision
One solution to get name of color may be by comparison like this :
    public static String getNameByComparision(Color color) {
        if (color.equals(Color.RED)) {
            return "RED";
        }
        if (color.equals(Color.BLACK)) {
            return "BLACK";
        }
        // ..
        return "NOT_DEFINED";
    }

cygwin: access windows disk, directories and files

Cygwin is a Open-source Linux-like environment for Windows. In this tutorial, I am going to show how we can access the windows directories and files using cygwin.