Sunday 19 February 2017

Object and face detection in OpenCv java

       
package com.test.motion.detection;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.highgui.Highgui;
import org.opencv.highgui.VideoCapture;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

public class MyTest {
 static OpenCVWindow openCVWindow,openCVWindow1;
    static Mat image;
 public static void main(String[] args) {
  
  System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  openCVWindow=new OpenCVWindow(1000,600);
  openCVWindow1=new OpenCVWindow(600,600);
       readImgFromCam();  
 }
 public static void readImgFromCam() {
  try {
   image=Highgui.imread("C:/Users/kiit1/Desktop/noface.jpg");
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  CascadeClassifier faceDetector = new CascadeClassifier("D:/javaTech/OpenCV/opencv/sources/data/lbpcascades/lbpcascade_frontalface.xml");
  
  VideoCapture cam=new VideoCapture(0);//"D:\\karana\\aVid.MP4"
  while(true){
 
   if(!cam.isOpened()){
    cam.open(0);
    System.out.println("No cam Found....");
   }else {
    }
   Mat frameMat=new Mat();
   Mat newmMat=new Mat();
   Mat cropImg=new Mat();
   MatOfRect matOfRect=new MatOfRect();
   //
   Mat blurredImage = new Mat();
   Mat hsvImage = new Mat();
   Mat mask = new Mat();
   Mat morphOutput = new Mat();
   Mat frame;
   cam.read(frameMat);
   Imgproc.resize(frameMat, newmMat, new Size(1000,600));
      
   frame=newmMat;
   Imgproc.blur(frame, blurredImage, new Size(7, 7));
   
   Imgproc.cvtColor(blurredImage, hsvImage, Imgproc.COLOR_BGR2HSV);
   
   Scalar minValues = new Scalar(0, 0,0);
   Scalar maxValues = new Scalar(180, 180,180);
   
   
   Core.inRange(hsvImage,minValues, maxValues, mask);
   // morphological operators
   // dilate with large element, erode with small ones
   Mat dilateElement = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(24, 24));
   Mat erodeElement = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(12, 12));
   
   Imgproc.erode(mask, morphOutput, erodeElement);
   Imgproc.erode(mask, morphOutput, erodeElement);//openCVWindow.showImage(morphOutput);
   
   Imgproc.dilate(mask, morphOutput, dilateElement);
   Imgproc.dilate(mask, morphOutput, dilateElement);
   
   frame = findAndDrawBalls(morphOutput, frame);
   
   faceDetector.detectMultiScale(newmMat, matOfRect);
   //for face detect
   for(Rect rect:matOfRect.toArray()){
   // Core.rectangle(new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
                    cropImg=newmMat.submat(rect);
          Core.rectangle(newmMat, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
   }
   try{
   openCVWindow1.showImage(cropImg); 
   }catch(Exception e){
    openCVWindow1.showImage(image);
   }
   //openCVWindow.showImage(frame);
   openCVWindow.showImage(newmMat);

   
  }
  //cam.release();
  

  
 }
 private static Mat findAndDrawBalls(Mat maskedImage, Mat frame)
 {
  // init
  List<MatOfPoint> contours = new ArrayList<>();
  Mat hierarchy = new Mat();
  
  // find contours
  Imgproc.findContours(maskedImage, contours, hierarchy, Imgproc.RETR_CCOMP, Imgproc.CHAIN_APPROX_SIMPLE);
  
  // if any contour exist...
  if (hierarchy.size().height > 0 && hierarchy.size().width > 0)
  {
   // for each contour, display it in blue
   for (int idx = 0; idx >= 0; idx = (int) hierarchy.get(0, idx)[0])
   {
    Imgproc.drawContours(frame, contours, idx, new Scalar(250, 0, 0));
   }
  }
  
  return frame;
 }
 

}



import java.awt.Dimension;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.highgui.Highgui;

public class OpenCVWindow extends JFrame{
 
 private static final long serialVersionUID = 1L;
 Sheet sheet;
 int height, width;


 public OpenCVWindow( int length, int breadth)
 {
  width = length;
  height = breadth;
  sheet = new Sheet(breadth,length);
  
  this.setSize(new Dimension(length, breadth));
  this.add(sheet);

  this.setFocusable(true);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setVisible(true);
  
 }
 


 public void showImage(Mat m)
 {
  MatOfByte matOfByte = new MatOfByte();
  Highgui.imencode(".jpg", m, matOfByte);
  
  byte[] byteArray = matOfByte.toArray();
  try
  {

   InputStream in = new ByteArrayInputStream(byteArray);
   sheet.paintSheet(ImageIO.read(in));
   
  } catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}

import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

public class Sheet extends JPanel
{
 private static final long serialVersionUID = 1L;
 BufferedImage image;
 int width, height;

 public Sheet( int h, int w)
 {
  width = w;
  height = h;

  setSize(w, h);
 }

 public void paintSheet(BufferedImage img)
 {
  image = img;
  repaint();
 }

 public void paintComponent(Graphics g)
 {
  g.drawImage(image, 0, 0, width, height, this);
 }
}

                                          OUTPUT

Friday 10 February 2017

Face detection by video processing in Java Using Open CV !

Please setup Your IDE For OpenCV


       
package com.test.motion.detection;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.highgui.VideoCapture;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

public class MyTest {
 static OpenCVWindow openCVWindow;
  
 public static void main(String[] args) {
  System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  openCVWindow=new OpenCVWindow(1000,600);

       readImgFromCam();  
 }
 public static void readImgFromCam() {
  CascadeClassifier faceDetector = new CascadeClassifier("D:/javaTech/OpenCV/opencv/sources/data/lbpcascades/lbpcascade_frontalface.xml");
  
  VideoCapture cam=new VideoCapture(0);
  while(true){
   
   if(!cam.isOpened()){
    cam.open(0);
    System.out.println("No cam Found....");
   }else {
    }
   Mat frameMat=new Mat();
   Mat newmMat=new Mat();
   MatOfRect matOfRect=new MatOfRect();
      
   
   cam.read(frameMat);
   Imgproc.resize(frameMat, newmMat, new Size(1000,600));
   
   faceDetector.detectMultiScale(newmMat, matOfRect);
   
   for(Rect rect:matOfRect.toArray()){
   // Core.rectangle(new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));

          Core.rectangle(newmMat, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
   }
   
   openCVWindow.showImage(newmMat);
   

   
  }
  //cam.release();
  

  
 }

}



 package com.test.motion.detection;

import java.awt.Dimension;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.highgui.Highgui;

public class OpenCVWindow extends JFrame{
 
 private static final long serialVersionUID = 1L;
 Sheet sheet;
 int height, width;


 public OpenCVWindow( int length, int breadth)
 {
  width = length;
  height = breadth;
  sheet = new Sheet(breadth,length);
  
  this.setSize(new Dimension(length, breadth));
  this.add(sheet);

  this.setFocusable(true);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setVisible(true);
  
 }
 


 public void showImage(Mat m)
 {
  MatOfByte matOfByte = new MatOfByte();
  Highgui.imencode(".jpg", m, matOfByte);
  
  byte[] byteArray = matOfByte.toArray();
  try
  {

   InputStream in = new ByteArrayInputStream(byteArray);
   sheet.paintSheet(ImageIO.read(in));
   
  } catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}

package com.test.motion.detection;

import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

public class Sheet extends JPanel
{
 private static final long serialVersionUID = 1L;
 BufferedImage image;
 int width, height;

 public Sheet( int h, int w)
 {
  width = w;
  height = h;

  setSize(w, h);
 }

 public void paintSheet(BufferedImage img)
 {
  image = img;
  repaint();
 }

 public void paintComponent(Graphics g)
 {
  g.drawImage(image, 0, 0, width, height, this);
 }
}


OUTPUT




Wednesday 8 February 2017

How to watch a folder in Java ?

       
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class MainWatch {

    public static void watchDirectoryPath(Path path) {
        // Sanity check - Check if path is a folder
        try {
            Boolean isFolder = (Boolean) Files.getAttribute(path,
                    "basic:isDirectory", NOFOLLOW_LINKS);
            if (!isFolder) {
                throw new IllegalArgumentException("Path: " + path
                        + " is not a folder");
            }
        } catch (IOException ioe) {
            // Folder does not exists
            ioe.printStackTrace();
        }

        System.out.println("Watching path: " + path);

        // We obtain the file system of the Path
        FileSystem fs = path.getFileSystem();

        // We create the new WatchService using the new try() block
        try (WatchService service = fs.newWatchService()) {

            // We register the path to the service
            // We watch for creation events
            path.register(service, ENTRY_CREATE,ENTRY_MODIFY,ENTRY_DELETE);
            
            // Start the infinite polling loop
            WatchKey key = null;
            while (true) {
                key = service.take();

                // Dequeueing events
                Kind<?> kind = null;
                for (WatchEvent<?> watchEvent : key.pollEvents()) {
                    // Get the type of the event
                    kind = watchEvent.kind();
                    if (OVERFLOW == kind) {
                        continue; // loop
                    } else if (ENTRY_CREATE == kind) {
                        // A new Path was created
                        Path newPath = ((WatchEvent<Path>) watchEvent)
                                .context();
                        // Output
                        System.out.println("New path created: " + newPath);
                    } else if (ENTRY_MODIFY == kind) {
                        // modified
                        Path newPath = ((WatchEvent<Path>) watchEvent)
                                .context();
                        // Output
                        System.out.println("New path modified: " + newPath);
                    }
                }

                if (!key.reset()) {
                    break; // loop
                }
            }

        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }

    }

    public static void main(String[] args) throws IOException,
            InterruptedException {
        
        File dir = new File("D:\\");
        watchDirectoryPath(dir.toPath());
    }
    }