/src/Blobs.java
Java | 80 lines | 58 code | 20 blank | 2 comment | 5 complexity | 1076c3d3993242a7b0952dbf5cf401b8 MD5 | raw file
- import java.awt.image.BufferedImage;
- import static com.googlecode.javacv.cpp.opencv_core.*;
- import static com.googlecode.javacv.cpp.opencv_imgproc.*;
- import static com.googlecode.javacv.cpp.opencv_highgui.*;
- import java.io.File;
- import java.io.IOException;
- import java.util.ArrayList;
- import javax.imageio.ImageIO;
- import com.googlecode.javacpp.Loader;
- import com.googlecode.javacv.cpp.opencv_core.CvPoint;
- import com.googlecode.javacv.cpp.opencv_core.CvPoint2D32f;
- import com.googlecode.javacv.cpp.opencv_core.CvScalar;
- import com.googlecode.javacv.cpp.opencv_core.IplImage;
- import com.googlecode.javacv.cpp.opencv_imgproc;
-
-
- public class Blobs {
-
- public static void main(String[] args) throws IOException
- {
- File file1 = new File("before.jpg");
- File file2 = new File("after.jpg");
-
- BufferedImage bimage1 = ImageIO.read(file1);
- IplImage before = IplImage.createFrom(bimage1);
-
- BufferedImage bimage2 = ImageIO.read(file2);
- IplImage after = IplImage.createFrom(bimage2);
-
-
- IplImage diff = IplImage.createCompatible(before);
-
- IplImage src = cvLoadImage("example.jpg");
- cvAbsDiff(before, after, diff);
-
- IplImage diffg = IplImage.create(cvGetSize(before),8,1);
- opencv_imgproc.cvCvtColor(diff, diffg, CV_RGB2GRAY);
-
- // thresholding (keep only pixels whose difference is larger than 50
- cvThreshold(diffg, diffg, 200, 255, CV_THRESH_BINARY);
-
- // find connected components
- final ArrayList<CvRect> blobs = detectBlobs(diffg);
-
- for (CvRect blob : blobs)
- {
- System.out.println("location of this blob:" + blob.x() + "," + blob.y()+","+blob.width()+","+blob.height());
- CvPoint center = cvPointFrom32f(new CvPoint2D32f(blob.x(),blob.y()));
- cvCircle(src, center, 1, CvScalar.RED, 6, CV_AA, 0);
-
- }
- cvSaveImage("look.jpg", src);
- cvShowImage("Result",src);
- cvWaitKey(0);
- }
-
-
- public static ArrayList<CvRect> detectBlobs(IplImage input)
- {
- IplImage clone = input.clone();
- CvMemStorage storage = CvMemStorage.create();
- CvSeq contour = new CvSeq(null);
- cvFindContours(clone, storage, contour, Loader.sizeof(CvContour.class), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
-
- ArrayList<CvRect> rects = new ArrayList<CvRect>();
-
- while (contour != null && !contour.isNull())
- {
- if (contour.elem_size() > 0) {
- CvRect boundingRect = cvBoundingRect(contour,0);
- rects.add(boundingRect);
- }
- contour = contour.h_next();
- }
- return rects;
- }
-
-
-
- }