seven corners 保险:javacv

来源:百度文库 编辑:偶看新闻 时间:2024/04/30 12:58:29

JavaCV

Introduction

JavaCV first provides wrappers to commonly used libraries by researchers in the field of computer vision: OpenCV, FFmpeg, libdc1394, PGR FlyCapture, OpenKinect, videoInput, and ARToolKitPlus. The following classes, found under the com.googlecode.javacv.cpp package namespace, expose their complete APIs: opencv_core, opencv_imgproc, opencv_video, opencv_flann, opencv_features2d, opencv_calib3d, opencv_objdetect, opencv_highgui, opencv_legacy, opencv_ml, opencv_contrib, avutil, avcodec, avformat, avdevice, avfilter, postproc, swscale, dc1394, PGRFlyCapture, freenect, videoInputLib, and ARToolKitPlus, respectively. Moreover, utility classes make it easy to use their functionality on the Java platform, including Android.

JavaCV also comes with hardware accelerated full-screen image display (CanvasFrame), easy-to-use methods to execute code in parallel on multiple cores (Parallel), user-friendly geometric and color calibration of cameras and projectors (GeometricCalibrator, ProCamGeometricCalibrator, ProCamColorCalibrator), detection and matching of feature points (ObjectFinder), a set of classes that implement direct image alignment of projector-camera systems (mainly GNImageAligner, ProjectiveTransformer, ProjectiveGainBiasTransformer, ProCamTransformer, and ReflectanceInitializer), as well as miscellaneous functionality in the JavaCV class.

To learn how to use the API, since documentation currently lacks, please refer to the #Quick_Start_for_OpenCV section below as well as the sample programs, including one for Android, found in the samples directory. You may also find it useful to refer to the source code of ProCamCalib and ProCamTracker.

I will continue to add all code that I am developing for my doctoral research as I go.

Required Software

To use JavaCV, you will need to download and install the following software:

  • An implementation of Java SE 6 or 7
    • OpenJDK http://openjdk.java.net/install/ or
    • Sun JDK http://www.oracle.com/technetwork/java/javase/downloads/ or
    • IBM JDK http://www.ibm.com/developerworks/java/jdk/ or
    • Java SE for Mac OS X http://developer.apple.com/java/ etc.
  • OpenCV 2.3.1 http://sourceforge.net/projects/opencvlibrary/files/
    • Precompiled for Android 2.2 http://code.google.com/p/javacv/downloads/list

And please make sure your Java and OpenCV have the same bitness: 32-bit and 64-bit modules do not mix under any circumstances. Further, although not always required, some functionality of JavaCV also relies on:

  • FFmpeg 0.6.x or 0.7.x http://ffmpeg.org/download.html
    • Precompiled for Windows (last compatible build: 18-Apr-2011)
      • http://hawkeye.arrozcru.org/builds/win32/shared/
      • http://hawkeye.arrozcru.org/builds/win64/shared/
    • Precompiled for Android 2.2 http://code.google.com/p/javacv/downloads/list
  • libdc1394 2.1.x (Linux and Mac OS X) http://sourceforge.net/projects/libdc1394/files/
  • PGR FlyCapture 1.7~2.1 (Windows only) http://www.ptgrey.com/products/pgrflycapture/
  • OpenKinect http://openkinect.org/
  • Android SDK API 8~12 http://developer.android.com/sdk/

To modify the source code, please note that the project files were created for:

  • NetBeans 6.9 http://netbeans.org/downloads/
  • JavaCPP http://code.google.com/p/javacpp/
  • ARToolKitPlus 2.1.1t http://code.google.com/p/javacv/downloads/list

Please keep me informed of any updates or fixes you make to the code so that I may integrate them into the next release. Thank you!

And feel free to ask questions on the mailing list if you encounter any problems with the software! I am sure it is far from perfect...

Quick Start for OpenCV

First, put all the JAR files of JavaCV (javacpp.jar, javacv.jar, and javacv-*.jar) somewhere in your classpath, and make sure that the library files of OpenCV (*.so, *.dylib, or *.dll) can be found either in their default installation directory or in the system PATH, which under Windows includes the current working directory. (For answers to problems frequently encountered with OpenCV on the Windows platform, please refer to Common issues with OpenCV under Windows 7.) Here are some more specific instructions for common cases:

NetBeans (Java SE 6 or 7):

  • In the Projects window, right-click the Libraries node of your project, and select "Add JAR/Folder...".
  • Locate the JAR files, select them, and click OK.

Eclipse (Java SE 6 or 7):

  • Navigate to Project > Properties > Java Build Path > Libraries and click "Add External JARs..."
  • Locate the JAR files, select them, and click OK.

Eclipse (Android 2.2 or newer):

  • Follow the instructions on this page: http://developer.android.com/resources/tutorials/hello-world.html
  • Go to File > New > Folder, select your project as parent folder, type "libs/armeabi" as Folder name, and click Finish.
  • Copy javacpp.jar and javacv.jar in the newly created "libs" folder.
  • Extract directly all the *.so files from javacv-android-arm.jar as well as the ones from OpenCV-2.3.1-android-arm.zip in the newly created "libs/armeabi" folder, without creating any new subdirectories.
  • Navigate to Project > Properties > Java Build Path > Libraries and click "Add JARs..."
  • Select both javacpp.jar and javacv.jar from the newly created "libs" folder.

After that, the wrapper classes for OpenCV can automatically access all of its C/C++ API. The class definitions are basically ports to Java of the original include files in C, plus the missing functionality exposed only by the C++ API, and I deliberately decided to keep as much of the original syntax as possible. For example, here is a method that tries to load an image file, smooth it, and save it back to disk:

import static com.googlecode.javacv.cpp.opencv_core.*; 
import static com.googlecode.javacv.cpp.opencv_imgproc.*; 
import static com.googlecode.javacv.cpp.opencv_highgui.*; 
 
public class Smoother { 
    public static void smooth(String filename) {  
        IplImage image = cvLoadImage(filename); 
        if (image != null) { 
            cvSmooth(image, image, CV_GAUSSIAN, 3); 
            cvSaveImage(filename, image); 
            cvReleaseImage(image); 
        } 
    } 
}

JavaCV also comes with helper classes and methods on top of OpenCV to facilitate its integration to the Java platform. Here is a small demo program demonstrating the most frequently useful parts:

import com.googlecode.javacpp.Loader; 
import com.googlecode.javacv.*; 
import com.googlecode.javacv.cpp.*; 
import static com.googlecode.javacv.cpp.opencv_core.*; 
import static com.googlecode.javacv.cpp.opencv_imgproc.*; 
import static com.googlecode.javacv.cpp.opencv_calib3d.*; 
import static com.googlecode.javacv.cpp.opencv_objdetect.*; 
 
public class Demo { 
    public static void main(String[] args) throws Exception { 
        String classifierName = null; 
        if (args.length > 0) { 
            classifierName = args[0]; 
        } else { 
            System.err.println("Please provide the path to \"haarcascade_frontalface_alt.xml\"."); 
            System.exit(1); 
        } 
 
        // Preload the opencv_objdetect module to work around a known bug. 
        Loader.load(opencv_objdetect.class); 
 
        // We can "cast" Pointer objects by instantiating a new object of the desired class. 
        CvHaarClassifierCascade classifier = new CvHaarClassifierCascade(cvLoad(classifierName)); 
        if (classifier.isNull()) { 
            System.err.println("Error loading classifier file \"" + classifierName + "\"."); 
            System.exit(1); 
        } 
 
        // CanvasFrame is a JFrame containing a Canvas component, which is hardware accelerated. 
        // It can also switch into full-screen mode when called with a screenNumber. 
        CanvasFrame frame = new CanvasFrame("Some Title"); 
 
        // OpenCVFrameGrabber uses opencv_highgui, but other more versatile FrameGrabbers 
        // include DC1394FrameGrabber, FlyCaptureFrameGrabber, OpenKinectFrameGrabber, 
        // VideoInputFrameGrabber, and FFmpegFrameGrabber. 
        FrameGrabber grabber = new OpenCVFrameGrabber(0); 
        grabber.start(); 
 
        // FAQ about IplImage: 
        // - For custom raw processing of data, getByteBuffer() returns an NIO direct 
        //   buffer wrapped around the memory pointed by imageData. 
        // - To get a BufferedImage from an IplImage, you may call getBufferedImage(). 
        // - The createFrom() factory method can construct an IplImage from a BufferedImage. 
        // - There are also a few copy*() methods for BufferedImage<->IplImage data transfers. 
        IplImage grabbedImage = grabber.grab(); 
        int width  = grabbedImage.width(); 
        int height = grabbedImage.height(); 
        IplImage grayImage    = IplImage.create(width, height, IPL_DEPTH_8U, 1); 
        IplImage rotatedImage = grabbedImage.clone(); 
 
        // Let's create some random 3D rotation... 
        CvMat randomR = CvMat.create(3, 3), randomAxis = CvMat.create(3, 1); 
        // We can easily and efficiently access the elements of CvMat objects 
        // with the set of get() and put() methods. 
        randomAxis.put((Math.random()-0.5)/4, (Math.random()-0.5)/4, (Math.random()-0.5)/4); 
        cvRodrigues2(randomAxis, randomR, null); 
        double f = (width + height)/2.0;        randomR.put(0, 2, randomR.get(0, 2)*f); 
                                                randomR.put(1, 2, randomR.get(1, 2)*f); 
        randomR.put(2, 0, randomR.get(2, 0)/f); randomR.put(2, 1, randomR.get(2, 1)/f); 
        System.out.println(randomR); 
 
        // Objects allocated with a create*() or clone() factory method are automatically released 
        // by the garbage collector, but may still be explicitly released by calling release(). 
        CvMemStorage storage = CvMemStorage.create(); 
 
        // We can allocate native arrays using constructors taking an integer as argument. 
        CvPoint hatPoints = new CvPoint(3); 
 
        // Again, FFmpegFrameRecorder also exists as a more versatile alternative. 
        FrameRecorder recorder = new OpenCVFrameRecorder("output.avi", width, height); 
        recorder.start(); 
 
        while (frame.isVisible() && (grabbedImage = grabber.grab()) != null) { 
            // Let's try to detect some faces! but we need a grayscale image... 
            cvCvtColor(grabbedImage, grayImage, CV_BGR2GRAY); 
            CvSeq faces = cvHaarDetectObjects(grayImage, classifier, storage, 
                1.1, 3, CV_HAAR_DO_CANNY_PRUNING); 
            int total = faces.total(); 
            for (int i = 0; i < total; i++) { 
                CvRect r = new CvRect(cvGetSeqElem(faces, i)); 
                int x = r.x(), y = r.y(), w = r.width(), h = r.height(); 
                cvRectangle(grabbedImage, cvPoint(x, y), cvPoint(x+w, y+h), CvScalar.RED, 1, CV_AA, 0); 
 
                // To access the elements of a native array, use the position() method. 
                hatPoints.position(0).x(x-w/10)   .y(y-h/10); 
                hatPoints.position(1).x(x+w*11/10).y(y-h/10); 
                hatPoints.position(2).x(x+w/2)    .y(y-h/2); 
                cvFillConvexPoly(grabbedImage, hatPoints.position(0), 3, CvScalar.GREEN, CV_AA, 0); 
            } 
 
            // Let's find some contours! but first some thresholding... 
            cvThreshold(grayImage, grayImage, 64, 255, CV_THRESH_BINARY); 
 
            // To check if an output argument is null we may call either isNull() or equals(null). 
            CvSeq contour = new CvSeq(null); 
            cvFindContours(grayImage, storage, contour, Loader.sizeof(CvContour.class), 
                    CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE); 
            while (contour != null && !contour.isNull()) { 
                if (contour.elem_size() > 0) { 
                    CvSeq points = cvApproxPoly(contour, Loader.sizeof(CvContour.class), 
                            storage, CV_POLY_APPROX_DP, cvContourPerimeter(contour)*0.02, 0); 
                    cvDrawContours(grabbedImage, points, CvScalar.BLUE, CvScalar.BLUE, -1, 1, CV_AA); 
                } 
                contour = contour.h_next(); 
            } 
 
            cvWarpPerspective(grabbedImage, rotatedImage, randomR); 
 
            frame.showImage(rotatedImage); 
            recorder.record(rotatedImage); 
 
            cvClearMemStorage(storage); 
        } 
        recorder.stop(); 
        grabber.stop(); 
        frame.dispose(); 
    } 
}

Acknowledgments

I am currently an active member of the Okutomi & Tanaka Laboratory, Tokyo Institute of Technology, supported by a scholarship from the Ministry of Education, Culture, Sports, Science and Technology (MEXT) of the Japanese Government.

Changes

October 1, 2011

  • Fixed DC1394FrameGrabber and FlyCaptureFrameGrabber to behave as expected with all Bayer/Raw/Mono/RGB/YUV cameras modes (within the limits of libdc1394 and PGR FlyCapture) ( issue #91 )
  • Fixed regression of IplImage.copyFrom() and createFrom() with BufferedImage objects of SinglePixelPackedSampleModel ( issue #102 )
  • C++ functions using std::vector objects as output parameters now work on Windows Vista and Windows 7 as well

August 20, 2011

  • Upgraded support to OpenCV 2.3.1
  • An output argument of type cv::Mat or cv::OutputArray returned with a size 0 now correctly sets CvArr.address = 0
  • Fixed IplImage.createFrom() and copyFrom() when called on objects returned by BufferedImage.getSubimage()
  • Added missing allocator to CvRNG
  • OpenCVFrameGrabber now detects when CV_CAP_PROP_POS_MSEC is broken and gives up calling cvGetCaptureProperty()
  • New OpenKinectFrameGrabber.grabDepth() and grabVideo() methods to capture "depth" and "video" simultaneously, regardless of the mode