simple ball game by colored object motion tracking - image processing opencv javacv

DEMO VIDEO:  simple ball game by colored object motion tracking - using javacv opencv to detect the path of moving object. This is earliest version of the game.


Full Code :
Java Collision Detection and bounce

Colored object tracking in java- javacv code


You need to integrate the ideas from above links.
The full (integrated code will be uploaded shortly)

most Guaranteed job forever - programming

Programming is basically guaranteed employment forever ?


So, my summary line is rather hyperbolic, but I firmly believe that there is almost no better skill to learn than computer programming.  It's impossible to predict what jobs will be most in demand in the future, and thirty years ago I probably would've told you that the world will always need typewriter repairers, but computers and computer software are here for the long haul, and being an expert on exactly how they work will be a very good thing to be.  Even if "programming" isn't exactly where it's at in another thirty years, it'll be a good stepping stone.



For the now, there are available jobs programming in almost every city in the civilized world.  If you're a good programmer and interview well, you could probably work for any city you wanted to with almost any company.  That said, it's a little easier to spot a bad programmer in an interview than it is to spot a bad lawyer or a bad accountant, so if you're NOT that great a programmer or you interview very poorly, those jobs may not be as open to you.

So hopefully I've established that being a programmer is one of the best career choices you can possibly make, unless you want to go with being a lawyer or a doctor or an oil baron.  Still, the important thing is that you enjoy it.  Learn programming because programming interests you, that's the important thing.  I know some programmers who did it for the money.  They turn out to be bad programmers, and, worse, they hate their jobs.  Do what you love, even if you end up poor and doing what you love.  Really.

So now your question is "how."  That's tougher.  You can learn in lots of ways.  One way would be to pick up pretty much any programming language.  Once you've learned how to think like a programmer, you're 90% of the way there.  Learn Java, C, or whatever you like.  The best advice I can give you is to think of a very, very, VERY small program to write (tic tac toe), and then go out and write that program.  Pick any language you like and feel free to switch.  Java's a decent starting language, but there are plenty of choices.

One of the first thing you'll realize about programmers is that when multiple choices are roughly equivalent, fierce camps will emerge on all sides.  "What language should Ilearn first" is a good example.  Some folks will insist that you learn by writing programs exclusively on paper in a made-up language.

Getting help and reading tutorials are good things.  If you're in school, try to take programming classes.  If you're out of school, it's harder.  Beware of the books like "Learn Everything About Being a Java Programmer in 7 Days and Also Get Certified."  Some of these are good, but most are bad.  On the other hand, it's not a bad idea to wander around the computer section of the bookstore or library and thumb through everything that looks interesting.  The more ideas you're exposed to, the better.

I can't overemphasize the importance of play.  Write little 5-10 line programs to do whatever.  Try them out.  Change them around and see what they do.  Grab small example programs and add a feature.

Programming friends are important.  Find a friend who's a decent programmer and pester them with all sorts of questions about particular things you're stuck with or don't understand.  Askville's not a bad place to ask specific questions, either.

# Sites to ask programming QA

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.

Java: Screen Capture using Robot and save

Robot : java.awt.Robot  is used to take control of the mouse and keyboard. It is used for test automation, self-running demos and screen capture at various state of execution of the program.
Java Code for detecting screen size and capturing whole screen using Robot and saving :

Java Collision Detection and bounce - Complete example source code download

Complete example of simple collision detection and bounce between circle-circle and ball-rectangular wall.

java collision detection 
Download Full source code : - Can be used in building simple games

Similar posts with little explanations :

Java Collision Detection and bounce- two circles collision and response

Collision detection between two circles and their response - Java source code - working

    public static void intersect(Ball a, Ball b) {
        //ref http://gamedev.stackexchange.com/questions/20516/ball-collisions-sticking-together
        double xDist, yDist;
        xDist = a.x - b.x;
        yDist = a.y - b.y;
        double distSquared = xDist * xDist + yDist * yDist;
        // Check the squared distances instead of the the distances, same
        // result, but avoids a square root.
        if (distSquared <= (a.radius + b.radius) * (a.radius + b.radius)) {
            double speedXocity = b.speedX - a.speedX;
            double speedYocity = b.speedY - a.speedY;
            double dotProduct = xDist * speedXocity + yDist * speedYocity;
            // Neat vector maths, used for checking if the objects moves towards
            // one another.
            if (dotProduct > 0) {
                double collisionScale = dotProduct / distSquared;
                double xCollision = xDist * collisionScale;
                double yCollision = yDist * collisionScale;
                // The Collision vector is the speed difference projected on the
                // Dist vector,
                // thus it is the component of the speed difference needed for
                // the collision.
                double combinedMass = a.getMass() + b.getMass();
                double collisionWeightA = 2 * b.getMass() / combinedMass;
                double collisionWeightB = 2 * a.getMass() / combinedMass;
                a.speedX += (collisionWeightA * xCollision);
                a.speedY += (collisionWeightA * yCollision);
                b.speedX -= (collisionWeightB * xCollision);
                b.speedY -= (collisionWeightB * yCollision);
            }
        }
    }

Java Collision Detection and bounce - Circle and rectangle

Collision detection between circle(any object) and rectangular wall is simple.
For collision detection we simply compare the distances. And if collision between ball and wall is detected, we change the directions of their speeds for bouncing the ball.

Here is the code:

Collision Detection of two circles - Simple Java Code

Java : Drawing of two circles, mouse motion event handler on one circle, and detect collision with other.

Determining whether or not two circles intersect or overlap or collide is done by comparing the distance between the two circles to the sum of radius of the two circles.


Full working code for collision detection only download here: 


Steps
1)Find the distance between the centers of the two circles(a and b) using the distance formula
 float dxSq = (a.x - b.x) * (a.x - b.x);
 float dySq = (a.y - b.y) * (a.y - b.y);
 int d = (int) Math.sqrt(dxSq + dySq);

2)Then the distance is compared with the radii .
    int r1Pr2 = (int) (a.radius + b.radius);
    if (d < r1Pr2) {
        System.out.println("Collided");
    } else if (d == r1Pr2) {
        System.out.println("Just touching");
    } 



Collision detection and response - bounce examples

JavaCV - Color based thresholding in image using OpenCV

JavaCV - Red color based thresholding (RGB-A space) in image using OpenCV : Full working java source code 


Note that the order of colors is BGR-A not RGB-A. 
Read it more from http://stackoverflow.com/questions/367449/bgr-color-space
//static 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.*;
//non-static imports
import com.googlecode.javacv.cpp.opencv_core.CvScalar;
import com.googlecode.javacv.cpp.opencv_core.IplImage;

JavaCV capture-save-flip-show live camera

NOTE: Updated code with configuration and example is available here:


--

JavaCV:  Capture/save/flip image and show live image on CanvasFrame from camera

JAVA CODE:
import static com.googlecode.javacv.cpp.opencv_core.cvFlip;
import static com.googlecode.javacv.cpp.opencv_highgui.cvSaveImage; import com.googlecode.javacv.CanvasFrame; import com.googlecode.javacv.FrameGrabber; import com.googlecode.javacv.VideoInputFrameGrabber; import com.googlecode.javacv.cpp.opencv_core.IplImage; public class GrabberShow implements Runnable { //final int INTERVAL=1000;///you may use interval IplImage image; CanvasFrame canvas = new CanvasFrame("Web Cam"); public GrabberShow() { canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE); } @Override public void run() { FrameGrabber grabber = new VideoInputFrameGrabber(0); // 1 for next camera int i=0; try { grabber.start(); IplImage img; while (true) { img = grabber.grab(); if (img != null) { cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise cvSaveImage((i++)+"-aa.jpg", img); // show image on window canvas.showImage(img); } //Thread.sleep(INTERVAL); } } catch (Exception e) { } }

public static void main(String[] args) { GrabberShow gs = new GrabberShow(); Thread th = new Thread(gs); th.start(); } }

Java Code : Capture Image from webcam using JavaCV

Java Code for capturing image from webcam- uses JavaCV (java wrapper for OpenCV) library
Working CODE:
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage; import static com.googlecode.javacv.cpp.opencv_highgui.*; public class CaptureImage { private static void captureFrame() { // 0-default camera, 1 - next...so on final OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0); try { grabber.start(); IplImage img = grabber.grab(); if (img != null) { cvSaveImage("capture.jpg", img); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { captureFrame(); } }

JavaCV- Image load, smooth and save

Static Imports:
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
import static com.googlecode.javacv.cpp.opencv_highgui.*;

Image Smoothing:
public static void smoothSave(String filename) throws Exception {
IplImage image = cvLoadImage(filename);
System.out.println(image.nSize());
if (image != null) {
cvSmooth(image, image, CV_BLUR, 3);
cvSaveImage("smoothed_" + filename, image);
cvReleaseImage(image);
}
}

OpenCV-JavaCV : eclipse project configuration windows 7

NOTE: A Easier and Simpler version of the installation step is available !!  Check the latest ( Jan , 2017) article.

---

Eclipse (windows 7) project setup for JNA wrapper of OpenCV : JavaCV - getting started.

OpenCV (Open Source Computer Vision Library) is library of programming functions for real time computer vision.  JavaCV provides wrappers to commonly used libraries for OpenCV and few others.

Download the Essentials :

CSS Format Source Code in blog articles - blogger, wordpress

CSS script to format source code in blog posting in blogger, wordpress... articles.


The working css script : Source Code Formatter CSS Script
<pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
            color: #000000; background-color: #eee;
            font-size: 12px; border: 1px dashed #999999;
            line-height: 14px; padding: 5px; 
            overflow: auto; width: 100%">
   <code style="color:#000000;word-wrap:normal;">
        
        <<<<YOUR CODE HERE>>>>
   
   </code>
</pre>

HTML/XML Tag Parsing using Regex in Java

This time, I am going to show how to parse the html tags like : 
xx <tag a ="b" c=  'd' e=f> yy </tag> zz

(Did you noticed the single,double and no-quote attribute values and spaces ? It is important to consider all these variations.)

Android Reverse Engineering - decompile .apk-.dex-.jar-.java

Reverse engineering of android java app using apktool, dex2jar, jd-gui to convert .apk file to .java.
By reverse engineering of android app (.apk file) we can get following :