PageRenderTime 113ms CodeModel.GetById 40ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Blobs.java

https://bitbucket.org/yan_chen/pc-image-processing
Java | 80 lines | 58 code | 20 blank | 2 comment | 5 complexity | 1076c3d3993242a7b0952dbf5cf401b8 MD5 | raw file
  1. import java.awt.image.BufferedImage;
  2. import static com.googlecode.javacv.cpp.opencv_core.*;
  3. import static com.googlecode.javacv.cpp.opencv_imgproc.*;
  4. import static com.googlecode.javacv.cpp.opencv_highgui.*;
  5. import java.io.File;
  6. import java.io.IOException;
  7. import java.util.ArrayList;
  8. import javax.imageio.ImageIO;
  9. import com.googlecode.javacpp.Loader;
  10. import com.googlecode.javacv.cpp.opencv_core.CvPoint;
  11. import com.googlecode.javacv.cpp.opencv_core.CvPoint2D32f;
  12. import com.googlecode.javacv.cpp.opencv_core.CvScalar;
  13. import com.googlecode.javacv.cpp.opencv_core.IplImage;
  14. import com.googlecode.javacv.cpp.opencv_imgproc;
  15. public class Blobs {
  16. public static void main(String[] args) throws IOException
  17. {
  18. File file1 = new File("before.jpg");
  19. File file2 = new File("after.jpg");
  20. BufferedImage bimage1 = ImageIO.read(file1);
  21. IplImage before = IplImage.createFrom(bimage1);
  22. BufferedImage bimage2 = ImageIO.read(file2);
  23. IplImage after = IplImage.createFrom(bimage2);
  24. IplImage diff = IplImage.createCompatible(before);
  25. IplImage src = cvLoadImage("example.jpg");
  26. cvAbsDiff(before, after, diff);
  27. IplImage diffg = IplImage.create(cvGetSize(before),8,1);
  28. opencv_imgproc.cvCvtColor(diff, diffg, CV_RGB2GRAY);
  29. // thresholding (keep only pixels whose difference is larger than 50
  30. cvThreshold(diffg, diffg, 200, 255, CV_THRESH_BINARY);
  31. // find connected components
  32. final ArrayList<CvRect> blobs = detectBlobs(diffg);
  33. for (CvRect blob : blobs)
  34. {
  35. System.out.println("location of this blob:" + blob.x() + "," + blob.y()+","+blob.width()+","+blob.height());
  36. CvPoint center = cvPointFrom32f(new CvPoint2D32f(blob.x(),blob.y()));
  37. cvCircle(src, center, 1, CvScalar.RED, 6, CV_AA, 0);
  38. }
  39. cvSaveImage("look.jpg", src);
  40. cvShowImage("Result",src);
  41. cvWaitKey(0);
  42. }
  43. public static ArrayList<CvRect> detectBlobs(IplImage input)
  44. {
  45. IplImage clone = input.clone();
  46. CvMemStorage storage = CvMemStorage.create();
  47. CvSeq contour = new CvSeq(null);
  48. cvFindContours(clone, storage, contour, Loader.sizeof(CvContour.class), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
  49. ArrayList<CvRect> rects = new ArrayList<CvRect>();
  50. while (contour != null && !contour.isNull())
  51. {
  52. if (contour.elem_size() > 0) {
  53. CvRect boundingRect = cvBoundingRect(contour,0);
  54. rects.add(boundingRect);
  55. }
  56. contour = contour.h_next();
  57. }
  58. return rects;
  59. }
  60. }