ミムの部屋

社内SEが,興味をもったことを書いていきます.

OpenCVのインストール・チュートリアル(Mac, eclipse, java)

今回は,OpenCVのインストールします. 自分が行った手順で説明していきたいと思います.

  1. Sourceforgeからopencv-?.?.?.zipをダウンロード
  2. opencv-?.?.?.zipを解凍/
  3. 解凍されたディレクトopencv-?.?.?に移動
  4. ビルド用のディレクトリ作成
    • mkdir build
  5. ビルド用のディレクトリに移動
  6. Makefileを作って,コンパイルする.
    • cmake -DBUILD_SHARED_LIBS=OFF ..
    • make -j8

といった具合です.jarファイルのパスの通し方とかは参考サイトを見てもらったほうがいいと思います.
また,OpenCVの本家のサイトでのサンプルコードをopencvのパージョン3.0.0で実行しようとするとエラーが起きます. そのため,下にあるソースコードをコピペしてもらえれば,実行できるはずです. エラーが起きる原因については,参考サイトを参照してください.

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.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
// imread, imwrite, etc

//
// Detects faces in an image, draws boxes around them, and writes the results
// to "faceDetection.png".
//
class DetectFaceDemo {
  public void run() {
    System.out.println("\nRunning DetectFaceDemo");

    // Create a face detector from the cascade file in the resources
    // directory.
    CascadeClassifier faceDetector = new CascadeClassifier("data/lbpcascades/lbpcascade_frontalface.xml");
    Mat image = Imgcodecs.imread("images.jpg");// 入力ファイル名設定

    // Detect faces in the image.
    // MatOfRect is a special container class for Rect.
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);

    System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));

    // Draw a bounding box around each face.
    for (Rect rect : faceDetections.toArray()) {
        Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
        
    }

    // Save the visualized detection.
    String filename = "test01.png";// 出力ファイル名設定
    System.out.println(String.format("Writing %s", filename));
    Imgcodecs.imwrite(filename, image);
  }
}

public class Test {
  public static void main(String[] args) {
    System.out.println("Hello, OpenCV");

    // Load the native library.
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    new DetectFaceDemo().run();
  }
}

参考サイト