コード例 #1
0
  public static void main(String[] args) {

    // 指定读出的图片路径和输出的文件
    String inputImagePath =
        identificate.class.getClassLoader().getResource("hf.jpg").getPath().substring(1);
    String outputImageFile = "identificate.png";

    String xmlPath =
        identificate
            .class
            .getClassLoader()
            .getResource("cascade_storage.xml")
            .getPath()
            .substring(1);
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    CascadeClassifier faceDetector = new CascadeClassifier(xmlPath);
    Mat image = Highgui.imread(inputImagePath);
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);

    // 画出脸的位置
    for (Rect rect : faceDetections.toArray()) {
      Core.rectangle(
          image,
          new Point(rect.x, rect.y),
          new Point(rect.x + rect.width, rect.y + rect.height),
          new Scalar(0, 0, 255));
    }

    // 写入到文件
    Highgui.imwrite(outputImageFile, image);

    System.out.print("\nOK!");
  }
コード例 #2
0
 private void setImagesForDatabaseEdit() {
   for (int i = 0; i < faceImages.size(); i++) {
     Mat m = Highgui.imread(thisPerson.getFacesFolderPath() + "/" + i + ".jpg");
     if (m != null) {
       onFaceCaptured(m);
     }
   }
 }
コード例 #3
0
 public static Mat findCardNumber(String path) {
   Mat mat = Highgui.imread(path);
   int x = 0;
   int y = (int) (mat.height() * ((double) 30 / 54));
   int width = mat.cols();
   int height = (int) (mat.height() * ((double) 7 / 54));
   return mat.submat(new Rect(x, y, width, height));
 }
コード例 #4
0
 public SaliencyResult saliencyalgorithmInterface(ImageObj imgobj, String method) {
   // TODO Auto-generated method stub
   float min = Float.MAX_VALUE;
   float max = Float.MIN_VALUE;
   String imgpath = imgobj.getSourcePath();
   int k_num = imgobj.getK_num();
   SaliencyResult result = new SaliencyResult();
   Mat img = Highgui.imread(imgpath, Highgui.CV_LOAD_IMAGE_GRAYSCALE);
   Mat saliencyMap = new Mat();
   saliencyMap.create(img.rows(), img.cols(), CvType.CV_16U);
   int HistGram[] = new int[256];
   int Gray[] = new int[img.cols() * img.rows()];
   int Dist[] = new int[256];
   float DistMap[] = new float[img.rows() * img.cols()];
   for (int row = 0; row < img.rows(); row++) {
     int CurIndex = row * img.cols();
     for (int col = 0; col < img.cols(); col++) {
       HistGram[(int) (img.get(row, col)[0])]++;
       Gray[CurIndex] = (int) (img.get(row, col)[0]);
       CurIndex++;
     }
   }
   for (int Y = 0; Y < 256; Y++) {
     int Value = 0;
     for (int X = 0; X < 256; X++) Value += Math.abs(Y - X) * HistGram[X];
     Dist[Y] = Value;
   }
   for (int row = 0; row < img.rows(); row++) {
     int CurIndex = row * img.cols();
     for (int col = 0; col < img.cols(); col++) {
       DistMap[CurIndex] = Dist[Gray[CurIndex]];
       if (DistMap[CurIndex] < min) min = DistMap[CurIndex];
       if (DistMap[CurIndex] > max) max = DistMap[CurIndex];
       CurIndex++;
     }
   }
   for (int row = 0; row < img.rows(); row++) {
     int CurIndex = row * img.cols();
     for (int col = 0; col < img.cols(); col++) {
       saliencyMap.put(row, col, partTwo((DistMap[CurIndex] - min) / (max - min) * 255));
       CurIndex++;
     }
   }
   new findMarkUtil();
   int nums[] = null;
   if (method == "kmeans") {
     nums = findMarkUtil.findMarkUtil_kmeans(saliencyMap, k_num, 255, 0, 5);
   } else if (method == "random") {
     nums = findMarkUtil.findMarkUtil_random(saliencyMap, k_num, 255);
   }
   result.setK_num(k_num);
   result.setSource(imgpath);
   result.setResult(nums);
   result.setSaliency(saliencyMap);
   return result;
 }
コード例 #5
0
ファイル: GetPerson.java プロジェクト: euxuoh/EigenFace
  public static void main(String[] args) {
    System.loadLibrary("opencv_java2410");

    Mat src = Highgui.imread("img/hx_30.jpg", 0);
    Mat dst = new Mat();

    Imgproc.equalizeHist(src, dst);

    Highgui.imwrite("out/hx_30_src.jpg", src);
    Highgui.imwrite("out/hx_30.jpg", dst);
  }
コード例 #6
0
  public void templateMatching() {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    int match_method = 5;
    int max_Trackbar = 5;
    Mat data = Highgui.imread("images/training_data/1" + "/data (" + 1 + ").jpg");
    Mat temp = Highgui.imread("images/template.jpg");
    Mat img = data.clone();

    int result_cols = img.cols() - temp.cols() + 1;
    int result_rows = img.rows() - temp.rows() + 1;
    Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);

    Imgproc.matchTemplate(img, temp, result, match_method);
    Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());

    double minVal;
    double maxVal;
    Point minLoc;
    Point maxLoc;
    Point matchLoc;
    // minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );
    Core.MinMaxLocResult res = Core.minMaxLoc(result);

    if (match_method == Imgproc.TM_SQDIFF || match_method == Imgproc.TM_SQDIFF_NORMED) {
      matchLoc = res.minLoc;
    } else {
      matchLoc = res.maxLoc;
    }

    // / Show me what you got
    Core.rectangle(
        img,
        matchLoc,
        new Point(matchLoc.x + temp.cols(), matchLoc.y + temp.rows()),
        new Scalar(0, 255, 0));

    // Save the visualized detection.
    Highgui.imwrite("images/samp.jpg", img);
  }
コード例 #7
0
  // OpenCV code
  private void modifyImage(String fileName) {
    // Create a face detector from the cascade file
    CascadeClassifier faceDetector = new CascadeClassifier("haarcascade_frontalface_alt.xml");
    Mat image = Highgui.imread(fileName);

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

    // Blur each face
    for (Rect rect : faceDetections.toArray()) {
      Mat faceArea = image.submat(rect);
      Imgproc.blur(faceArea, faceArea, new Size(30, 30));
    }
    // Save the modified image
    Highgui.imwrite("edited_" + fileName, image);
  }
コード例 #8
0
 public void run() {
   System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
   MyCvWindow cvWindow = new MyCvWindow("sample", 512, 512);
   String filepath = getClass().getResource("lena.jpg").getPath();
   Mat image;
   while (true) {
     image = Highgui.imread(filepath);
     cvWindow.showImage(image);
     Point point = cvWindow.touchedPoint();
     if (point != null) {
       System.out.println("Point(" + point.x + "," + point.y + ")");
     }
     int key = cvWindow.waitKey(40);
     if (key == MyCvWindow.KEY_ESC) {
       System.exit(0);
     }
   }
 }
コード例 #9
0
ファイル: Main.java プロジェクト: joseluisdiaz/sudoku-solver
  public static void main(String[] args) {

    if (args.length < 1) {
      System.out.println("Filenamemissing");
      System.exit(-1);
    }

    Mat m = Highgui.imread(args[0]);

    DetectSudoku sudoku = new DetectSudoku();
    List<Integer> l = sudoku.extractDigits(m);

    Board b = Board.of(9, Joiner.on(" ").join(l));

    System.out.println("Grabbed sudoku\n==============\n\n");
    System.out.println(b);

    SudokuSolver s = new SudokuSolver(b);
    Board solved = s.solve();

    System.out.println("Solved sudoku\n=============\n\n");
    System.out.println(solved);
  }
コード例 #10
0
  public static void extractQueryFeatures2HDFS(String filename, Job job) throws IOException {

    // Read the local image.jpg as a Mat
    Mat query_mat_float =
        Highgui.imread(LOCAL_USER_DIR + ID + INPUT + "/" + filename, CvType.CV_32FC3);
    // Convert RGB to GRAY
    Mat query_gray = new Mat();
    Imgproc.cvtColor(query_mat_float, query_gray, Imgproc.COLOR_RGB2GRAY);
    // Convert the float type to unsigned integer(required by SIFT)
    Mat query_mat_byte = new Mat();
    query_gray.convertTo(query_mat_byte, CvType.CV_8UC3);
    //        // Resize the image to 1/FACTOR both width and height
    //        Mat query_mat_byte = FeatureExtraction.resize(query_mat_byte);

    // Extract the feature from the (Mat)image
    Mat query_features = FeatureExtraction.extractFeature(query_mat_byte);

    System.out.println(PREFIX + "Extracting the query image feature...");
    System.out.println("query_mat(float,color):" + query_mat_float);
    System.out.println("query_mat(float,gray):" + query_gray);
    System.out.println("query_mat(byte,gray):" + query_mat_byte);
    System.out.println("query_mat_features:" + query_features);
    System.out.println();

    // Store the feature to the hdfs in order to use it later in different map tasks
    System.out.println(PREFIX + "Generating the feature file for the query image in HDFS...");
    FileSystem fs = FileSystem.get(job.getConfiguration());
    String featureFileName = filename.substring(0, filename.lastIndexOf(".")) + ".json";
    FSDataOutputStream fsDataOutputStream =
        fs.create(new Path(HDFS_HOME + USER + ID + INPUT + "/" + featureFileName));
    BufferedWriter bw =
        new BufferedWriter(new OutputStreamWriter(fsDataOutputStream, StandardCharsets.UTF_8));
    bw.write(FeatureExtraction.mat2json(query_features));
    bw.close();
    System.out.println(PREFIX + "Query feature extraction finished...");
    System.out.println();
  }
コード例 #11
0
  /* (non-Javadoc)
   * @see java.lang.Runnable#run()
   */
  @Override
  public void run() {
    if (MODE.equals("VIDEO")) {
      Mat capturedImage = new Mat();
      VideoCapture vc = new VideoCapture(DEVICE);
      if (!vc.isOpened()) {
        System.out.println("Capture Failed!");
        return;
      }
      System.out.println("Device " + DEVICE + " opened");
      // set captured resolution
      vc.set(Highgui.CV_CAP_PROP_FRAME_WIDTH, 640);
      vc.set(Highgui.CV_CAP_PROP_FRAME_HEIGHT, 480);

      // Manually set exposure
      vc.set(15, -11);
      while (true) {
        vc.read(capturedImage);
        if (capturedImage != null) {
          // flip the image to compensate for camera orientation
          Core.flip(capturedImage, capturedImage, -1);
          capturedImage.copyTo(finalDisplayImg);
          parseImage(capturedImage);
        }
      }
    } else { // STILL IMAGE
      Mat capturedImage = Highgui.imread(IMAGE_FILEPATH);
      while (true) {
        if (needUpdate) {
          capturedImage.copyTo(finalDisplayImg);
          parseImage(capturedImage);
          needUpdate = false;
        }
      }
    }
  }
コード例 #12
0
ファイル: RechargeReturn.java プロジェクト: pcooksey/Lutra
  public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    img = inputFrame.rgba();
    endTime = System.currentTimeMillis();

    switch (viewMode) {
      case VIEW_MODE_RGBA:
      /** Detects the circles in the RGB format */
        frameCount++;
        drawCircles = false;
        /** Setting thrust */
        twist.dx(thrust);
        /** Flip image when using on boat */
        // Core.flip(img, img, 0);
        /** Convert it to hue, convert to range color, and blur to remove false circles */
        Imgproc.cvtColor(img, img_hue, Imgproc.COLOR_RGB2HSV);
        img_hue = InRangeCircles(img_hue);
        Imgproc.GaussianBlur(img_hue, img_hue, new Size(9, 9), 10, 10);

        /** Create mat for circles and apply the Hough Transform to find the circles */
        Mat circles = new Mat();
        Imgproc.HoughCircles(
            img_hue,
            circles,
            Imgproc.CV_HOUGH_GRADIENT,
            2,
            minDistance,
            70,
            20,
            minRadius,
            maxRadius);

        /** Draws the circles and angle */
        drawCircles(img, circles);
        break;

      case VIEW_MODE_BW:
      /** This mode displays image in black/white to show what the algorithm sees */
        Imgproc.cvtColor(img, img_hue, Imgproc.COLOR_RGB2HSV);
        img_hue = InRangeCircles(img_hue);
        Imgproc.GaussianBlur(img_hue, img, new Size(9, 9), 10, 10);
        break;

      case VIEW_MODE_PIC:
      /** Takes pictures every 20 frames */
        frameCount++;
        /// Need for normally saving raw photos
        Imgproc.cvtColor(img, img_hue, Imgproc.COLOR_RGB2BGR);
        Core.flip(img_hue, img_hue, 0);
        if (frameCount % 10 == 0) {
          // Imgproc.cvtColor(img, img_hue, Imgproc.COLOR_RGBA2BGR);
          Highgui.imwrite("/sdcard/TestPics/test" + frameCount / 10 + ".jpg", img_hue);
        }
        break;

      case VIEW_MODE_TEST:
      /** Testing mode for new code using the pictures as a simulation */
        frameCount++;
        fileNum++;
        if (fileNum > 175) {
          fileNum = 1;
        }
        Mat temp = Highgui.imread("/sdcard/TestPics/test" + fileNum + ".jpg");
        // Mat temp = Highgui.imread("/sdcard/TestPics/test17.jpg"); //120
        Imgproc.cvtColor(temp, img_hue, Imgproc.COLOR_BGR2HSV);
        // Imgproc.cvtColor(temp, temp, Imgproc.COLOR_BGR2RGB);
        img_hue = InRangeCircles(img_hue);
        Imgproc.GaussianBlur(img_hue, img_hue, new Size(9, 9), 10, 10);
        /** Create mat for circles and apply the Hough Transform to find the circles */
        Mat circles2 = new Mat();
        Imgproc.HoughCircles(
            img_hue,
            circles2,
            Imgproc.CV_HOUGH_GRADIENT,
            2,
            minDistance,
            70,
            20,
            minRadius,
            maxRadius);
        /** Draws the circles and angle */
        drawCircles(temp, circles2);
        // Highgui.imwrite("/sdcard/TestPics/test"+(fileNum+2)+".jpg", temp);
        // drawCircles(img_hue,circles2);
        startTime = System.currentTimeMillis();
        return temp;

      default:
        break;
    }

    startTime = System.currentTimeMillis();
    return img;
  }
コード例 #13
0
  public static void main(String[] args) {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    //      Mat mat = Mat.eye( 3, 3, CvType.CV_8UC1 );
    //      System.out.println( "mat = " + mat.dump() );

    Sample n = new Sample();
    //   n.templateMatching();

    // put text in image
    //      Mat data= Highgui.imread("images/erosion.jpg");

    //      Core.putText(data, "Sample", new Point(50,80), Core.FONT_HERSHEY_SIMPLEX, 1, new
    // Scalar(0,0,0),2);
    //
    //      Highgui.imwrite("images/erosion2.jpg", data);

    // getting dct of an image
    String path = "images/croppedfeature/go (20).jpg";
    path = "images/wordseg/img1.png";
    Mat image = Highgui.imread(path, Highgui.IMREAD_GRAYSCALE);
    ArrayList<MatOfPoint> contours = new ArrayList<MatOfPoint>();

    Imgproc.threshold(image, image, 0, 255, Imgproc.THRESH_OTSU);
    Imgproc.threshold(image, image, 220, 128, Imgproc.THRESH_BINARY_INV);
    Mat newImg = new Mat(45, 100, image.type());

    newImg.setTo(new Scalar(0));
    n.copyMat(image, newImg);

    int vgap = 25;
    int hgap = 45 / 3;

    Moments m = Imgproc.moments(image, false);
    Mat hu = new Mat();
    Imgproc.HuMoments(m, hu);
    System.out.println(hu.dump());

    //      //divide the mat into 12 parts then get the features of each part
    //      int count=1;
    //      for(int j=0; j<45; j+=hgap){
    //    	  for(int i=0;i<100;i+=vgap){
    //    		  Mat result = newImg.submat(j, j+hgap, i, i+vgap);
    //
    //
    //    		  Moments m= Imgproc.moments(result, false);
    //    		  double m01= m.get_m01();
    //    		  double m00= m.get_m00();
    //    		  double m10 = m.get_m10();
    //    		  int x= m00!=0? (int)(m10/m00):0;
    //    		  int y= m00!=0? (int)(m01/m00):0;
    //    		  Mat hu= new Mat();
    //    		  Imgproc.HuMoments(m, hu);
    //    		  System.out.println(hu.dump());
    //    		  System.out.println(count+" :"+x+" and "+y);
    //    		  Imgproc.threshold(result, result, 0,254, Imgproc.THRESH_BINARY_INV);
    //    		  Highgui.imwrite("images/submat/"+count+".jpg", result);
    //    		  count++;
    //
    //    	  }
    //      }
    //
    //    for(int i=vgap;i<100;i+=vgap){
    //	  Point pt1= new Point(i, 0);
    //      Point pt2= new Point(i, 99);
    //      Core.line(newImg, pt1, pt2, new Scalar(0,0,0));
    //  }
    //  for(int i=hgap;i<45;i+=hgap){
    //	  Point pt1= new Point(0, i);
    //      Point pt2= new Point(99, i);
    //      Core.line(newImg, pt1, pt2, new Scalar(0,0,0));
    //  }
    //      Highgui.imwrite("images/submat/copyto.jpg", newImg);
  }
コード例 #14
0
ファイル: HelloOpenCV.java プロジェクト: RuiOrey/Black
  public void run() {
    System.out.println("\nRunning DetectFaceDemo");

    // Create a face detector from the cascade file in the resources
    // directory.
    // String facefilterpath =
    // getClass().getResource("../resources/haarcascade_mcs_eyepair_big.xml").getPath();
    String facefilterpath = getClass().getResource("../resources/haarcascade_eye.xml").getPath();
    facefilterpath = facefilterpath.substring(1, facefilterpath.length());
    CascadeClassifier faceDetector = new CascadeClassifier(facefilterpath);
    String pngpath = getClass().getResource("../resources/brown_eyes.jpg").getPath();
    pngpath = pngpath.substring(1, pngpath.length());
    Mat image = Highgui.imread(pngpath);

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

    Mat image2 = image;

    Imgproc.cvtColor(image2, image, 6); // 6 = CV_BGR2GRAY not working
    Imgproc.GaussianBlur(image, image, new Size(7, 7), 4, 4);
    // Imgproc.medianBlur(image,image, 2);
    MatOfPoint3f circles = new MatOfPoint3f();
    MatOfPoint3f circles2 = new MatOfPoint3f();

    Imgproc.HoughCircles(
        image, circles, Imgproc.CV_HOUGH_GRADIENT, 5, image.rows() / 5, 100, 100, 10, 50);

    Imgproc.HoughCircles(
        image, circles2, Imgproc.CV_HOUGH_GRADIENT, 5, image.rows() / 5, 100, 100, 50, 400);

    Imgproc.cvtColor(image, image, 8); // 6 = CV_BGR2GRAY not working

    System.out.println(String.format("Detected %s faces", faceDetections));
    // Draw a bounding box around each face.
    for (Rect rect : faceDetections.toArray()) {
      // Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y +
      // rect.height), new Scalar(0, 255, 0),100);
    }

    System.out.println(String.format("Detected %s circles", circles.total()));

    for (Point3 circle : circles.toArray()) {
      Point center = new Point(circle.x, circle.y);
      int radius = (int) Math.round(circle.z);
      Core.circle(image, center, 3, new Scalar(0, 255, 0), -1, 8, 0);
      Core.circle(image, center, radius, new Scalar(0, 0, 255), 3, 8, 0);
      // Core.circle(image, center, radius, new Scalar(0,255,0), 10,8, 0);
    }
    for (Point3 circle : circles2.toArray()) {
      Point center = new Point(circle.x, circle.y);
      int radius = (int) Math.round(circle.z);
      Core.circle(image, center, 3, new Scalar(0, 255, 0), -1, 8, 0);
      Core.circle(image, center, radius, new Scalar(0, 0, 255), 3, 8, 0);
      // Core.circle(image, center, radius, new Scalar(0,255,0), 10,8, 0);
    }

    // Core.circle(image, new Point(100,100), 10, new Scalar(0,255,0), 10, 8, 0);
    // Save the visualized detection.

    String filename = "faceDetection.png";
    System.out.println(String.format("Writing %s", filename));
    Highgui.imwrite(filename, image);
  }
コード例 #15
0
ファイル: Square.java プロジェクト: emre801/PokeEye
 public static void loadSquareStuffBwahaha() {
   System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
   // System.out.println(input);
   Mat src = Highgui.imread(input);
   getSquare(src);
 }
コード例 #16
0
  public static void main(String[] args) {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    CameraParameters camParam;
    camParam = new CameraParameters();
    MarkerDetector mDetector;
    mDetector = new MarkerDetector();
    ArrayList<Marker> markers;
    markers = new ArrayList<>();
    BoardDetector bd;
    bd = new BoardDetector(true);
    Board board;
    board = new Board();
    BoardConfiguration boardC;
    boardC = new BoardConfiguration();
    FiducidalMarkers fm = new FiducidalMarkers();

    Mat img = Highgui.imread("/home/jayzeegp/NetBeansProjects/ProbandoAruco/img/image-test.png");

    mDetector.detect(img, markers, camParam, -1);
    ArrayList<Integer> excludedIds = new ArrayList<>();
    excludedIds.add(23);
    excludedIds.add(12);
    excludedIds.add(45);
    excludedIds.add(11);
    excludedIds.add(44);
    excludedIds.add(22);

    ArrayList<Point> puntos = new ArrayList();
    puntos.add(0, new Point(1.04, 4.50));
    puntos.add(1, new Point(1.05, 4.51));
    puntos.add(2, new Point(1.06, 4.52));
    puntos.add(3, new Point(1.07, 4.53));

    try {
      mDetector.warp(img, img, new Size(4, 4), puntos);
    } catch (Exception ex) {
      System.out.println(ex.getMessage());
    }
    /*
     try{
         //bd.detect(markers, boardC, board, camParam);
         //Mat returned = fm.createBoardImage(new Size(2,3), 50, 5, boardC, excludedIds);
         //Mat returned = fm.createBoardImage_ChessBoard(new Size(2,3), 60, boardC, false, excludedIds);
         Mat returned = fm.createBoardImage_Frame(new Size(2,3), 50, 5, boardC, false, excludedIds);
         MatOfByte matOfByte = new MatOfByte();

        Highgui.imencode(".jpg", returned, matOfByte);

        byte[] byteArray = matOfByte.toArray();
        BufferedImage bufImage = null;
        boardC.saveToFile("/home/jayzeegp/NetBeansProjects/ProbandoAruco/board.txt");
        try {
            InputStream in = new ByteArrayInputStream(byteArray);
            bufImage = ImageIO.read(in);
        } catch (Exception e) {
        }
       JLabel picLabel = new JLabel(new ImageIcon(bufImage));
       JFrame frame = new JFrame("Original");
       frame.add(picLabel);
       frame.pack();
       frame.setVisible(true);

     }catch(Exception e){
         System.out.println("Exception: " + e.getMessage());
     }



     for(int i=0;i<markers.size();i++){
         if(markers.get(i).isValid()){
            markers.get(i).draw(img, new Scalar(255,0,0));
         }
     }


     MatOfByte matOfByte = new MatOfByte();

     Highgui.imencode(".jpg", img, matOfByte);

     byte[] byteArray = matOfByte.toArray();
     BufferedImage bufImage = null;

     try {
         InputStream in = new ByteArrayInputStream(byteArray);
         bufImage = ImageIO.read(in);
     } catch (Exception e) {
                  System.out.println("Exception: " + e.getMessage());
     }
    JLabel picLabel = new JLabel(new ImageIcon(bufImage));
    JFrame frame = new JFrame("Original");
    frame.add(picLabel);
    frame.pack();
    frame.setVisible(true);
    Mat resultado;
    */

  }
コード例 #17
0
  public void btn_camera_ok(View view) {
    Log.i(TAG, "btn_camera_ok");
    if (!bPictaken) {
      ToastUtil.showShortToast(getApplicationContext(), "亲要先进行拍照哟!");
      return; // do not forget!
    }
    // async do -> runtime exception: method called after release()
    // maybe the activity releases before the thread returns!
    final Mat image = Highgui.imread(filePath);
    int width = image.width();
    int height = image.height();
    if (width > height) { // portrait should be rotated! direction? yes!
      Core.flip(image.t(), image, 0); // counter-clock wise 90
    }
    Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2GRAY); // gray
    Imgproc.resize(image, image, new Size(CommonUtil.IMAGE_WIDTH, CommonUtil.IMAGE_HEIGHT)); //
    int total = 0;
    String stotal = CommonUtil.userProps.getProperty("total");
    if (null != stotal) { // have some users!
      total = Integer.parseInt(stotal);
    }
    if (userid <= 0) { // not have this one!
      userid = total + 1;
      try { // save new data!
        CommonUtil.userProps.setProperty("total", String.valueOf(userid));
        CommonUtil.userProps.setProperty(String.valueOf(userid), name);
        CommonUtil.saveUserProperties(CommonUtil.userProps);
      } catch (Exception e) {
        e.printStackTrace();
      }
      // creat folder for this user!
      File userfolder =
          new File(
              CommonUtil.USERFOLDER.getAbsolutePath() + File.separator + String.valueOf(userid));
      if (!userfolder.exists()) {
        userfolder.mkdir();
      }
    }
    filePath =
        CommonUtil.USERFOLDER.getAbsolutePath()
            + File.separator
            + String.valueOf(userid)
            + File.separator
            + System.currentTimeMillis()
            + ".jpg"; // folder (user / userid)
    Highgui.imwrite(filePath, image);
    // save data to facedata.txt
    String data = filePath + ";" + userid + "\n"; // user image file path;user id
    try {
      RandomAccessFile facedataFile =
          new RandomAccessFile(
              CommonUtil.SDFOLDER + File.separator + CommonUtil.FACEDATA_FILENAME, "rw");
      facedataFile.seek(facedataFile.length());
      facedataFile.write(data.getBytes());
      facedataFile.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    Log.i(TAG, "image process ok");

    // add this pic to the model data
    new AsyncTask<Void, Void, Boolean>() {

      @Override
      protected Boolean doInBackground(Void... params) {
        xface.addImage(image, userid); // how to determinate the result of adding image?!TODO!
        return true;
      }

      @Override
      protected void onPostExecute(Boolean result) {
        if (result) {
          ToastUtil.showShortToast(getApplicationContext(), "照片保存成功,模型建立好咯!");
        } else {
          ToastUtil.showShortToast(getApplicationContext(), "照片保存成功,模型建立失败啦!");
        }
        btn_camera_ok.setEnabled(true);
      }

      @Override
      protected void onPreExecute() {
        ToastUtil.showShortToast(getApplicationContext(), "照片保存中...");
        btn_camera_ok.setEnabled(false); // can not let user save two images at the same time!
      }
    }.execute();
  }
コード例 #18
0
  public static void main(String[] args) {

    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    /** *** Configuration Variables **** */
    int imgWidth = 200;
    int imgHeight = 200;
    int numPatch = 2000;
    int patchWidth = 40;
    int patchHeight = 40;
    int k = 200; // kmeans number of center
    int numBins = 8;

    String filePathRed = "base/Red/";
    String filePathBlack = "base/Black";
    String procPathRed = "base/ProcRed";
    String procPathBlack = "base/ProcBlack";
    /** ******************************** */
    ArrayList<String> fileNames = new ArrayList<String>();

    sources = new ArrayList<Mat>();

    /* Image IO */
    try {

      /* Read Red Staplers */
      File folder = new File(filePathRed);
      BufferedImage currentImage;
      for (final File fileEntry : folder.listFiles()) {
        if (!fileEntry.isDirectory()) {

          // Resize Image
          currentImage = ImageProc.resize(ImageIO.read(fileEntry), imgWidth, imgHeight);

          File outFile = new File(procPathRed + "/" + fileEntry.getName());
          ImageIO.write(currentImage, "JPG", outFile);
          sources.add(Highgui.imread(outFile.getPath()));
          fileNames.add(outFile.getName());
        }
      }

      /* Read Black Staplers */
      folder = new File(filePathBlack);
      for (final File fileEntry : folder.listFiles()) {
        if (!fileEntry.isDirectory()) {

          // Resize Image
          currentImage = ImageProc.resize(ImageIO.read(fileEntry), imgWidth, imgHeight);

          File outFile = new File(procPathBlack + "/" + fileEntry.getName());
          ImageIO.write(currentImage, "JPG", outFile);
          sources.add(Highgui.imread(outFile.getPath()));
          fileNames.add(outFile.getName());
        }
      }

    } catch (IOException e) {
      e.printStackTrace();
    }

    /** ************************************* */
    float[] p1 = new float[30];
    float[] p2 = new float[30];

    /* Create Image Patches and calculate color feature vector for each patch */
    Iterator<Mat> imgIter = sources.iterator();
    Mat thisImage;
    Mat featureMat = new Mat();
    List<Mat> imagePatches = null;
    Iterator<Mat> patchIter = null;

    while (imgIter.hasNext()) {

      thisImage = imgIter.next();

      // Randomly Sample Patches
      imagePatches = ImageProc.sampleImage(thisImage, patchWidth, patchHeight, numPatch);
      patchIter = imagePatches.iterator();

      // Create color feature vector for each patch
      while (patchIter.hasNext()) {
        featureMat.push_back(ImageProc.calBGRFeature(patchIter.next(), numBins));
      }
    }

    Mat centers = new Mat();
    Mat bestLabels = new Mat();
    Core.kmeans(
        featureMat,
        k,
        bestLabels,
        new TermCriteria(TermCriteria.EPS, 0, Math.pow(10, -5)),
        0,
        Core.KMEANS_RANDOM_CENTERS,
        centers);

    MatOfFloat bestLabelRange = new MatOfFloat(0, k);

    ArrayList<Mat> centerHist = new ArrayList<Mat>();
    Mat centerHistMat = new Mat(0, k, CvType.CV_32FC1);

    imgIter = sources.listIterator();
    Iterator<String> nameIter = fileNames.iterator();

    int ptr = 0;
    int cnt = 0;

    // Output CSV

    try {
      File outCSV = new File("output/res.csv");
      FileWriter fstream = new FileWriter(outCSV);
      BufferedWriter out = new BufferedWriter(fstream);
      StringBuilder sb;
      out.write("@relation staplers\n");
      for (int n = 0; n < 200; n++) {
        out.write("@attribute " + "a" + n + " real\n");
      }

      out.write("@attribute class {RedStapler, BlackStapler}\n\n");
      out.write("@data\n\n");

      while (imgIter.hasNext()) {

        Mat thisMat = new Mat(bestLabels, new Range(ptr, ptr + numPatch), new Range(0, 1));
        Mat mat = new Mat();
        thisMat.convertTo(mat, CvType.CV_32F);

        ArrayList<Mat> bestLabelList = new ArrayList<Mat>();
        bestLabelList.add(mat);

        Mat thisHist = new Mat();
        Imgproc.calcHist(
            bestLabelList, new MatOfInt(0), new Mat(), thisHist, new MatOfInt(k), bestLabelRange);

        centerHist.add(thisHist);

        // Create file
        sb = new StringBuilder();

        float[] histArr = new float[(int) thisHist.total()];
        thisHist.get(0, 0, histArr);

        for (int m = 0; m < histArr.length; m++) {
          sb.append(histArr[m] + ",");
        }

        if (cnt++ < 10) sb.append("RedStapler");
        else sb.append("BlackStapler");

        sb.append("\n");
        out.write(sb.toString());
        // Close the output stream

        centerHistMat.push_back(thisHist.t());
        ptr += numPatch;
        imgIter.next();
      }

      out.close();
    } catch (IOException e) { // Catch exception if any
      System.err.println("Error: " + e.getMessage());
      System.exit(-1);
    }

    /* Support Vector Machine Validation */
    Mat labelMat = new Mat(sources.size(), 1, CvType.CV_32FC1);

    double[] labels = new double[20];
    for (int i = 0; i < 10; i++) {
      labels[i] = 1;
      labels[i + 10] = -1;
    }
    labelMat.put(0, 0, labels);

    CvSVMParams params = new CvSVMParams();
    params.set_kernel_type(CvSVM.LINEAR);

    CvSVM svm = new CvSVM();
    svm.train(centerHistMat, labelMat, new Mat(), new Mat(), params);
    svm.save("base/haha.txt");
    String basePath = "base/predict/";

    try {
      File testCSV = new File("output/test.arff");
      FileWriter testStream = new FileWriter(testCSV);
      BufferedWriter testOut = new BufferedWriter(testStream);

      testOut.write("@relation staplers\n");
      for (int n = 0; n < 200; n++) {
        testOut.write("@attribute " + "a" + n + " real\n");
      }

      testOut.write("@attribute class {RedStapler, BlackStapler}\n\n");
      testOut.write("@data\n\n");

      for (int m = 0; m < 21; m++) {

        // System.out.println(basePath + m + ".jpg");
        Mat testImg = Highgui.imread(basePath + m + ".jpg");

        List<Mat> patches = ImageProc.sampleImage(testImg, patchWidth, patchHeight, numPatch);
        List<Mat> features = new ArrayList<Mat>();

        for (int i = 0; i < patches.size(); i++) {

          Mat testVector = ImageProc.calBGRFeature(patches.get(i), numBins);
          features.add(testVector);
        }

        Mat testData = ImageProc.calFeatureVector(features, centers);

        StringBuilder testsb = new StringBuilder();
        // String name = nameIter.next();
        // sb.append(name + ",");

        float[] data = new float[testData.cols()];
        testData.get(0, 0, data);

        for (int o = 0; o < data.length; o++) {
          testsb.append(data[o] + ",");
        }
        if (m < 6) testsb.append("RedStapler");
        else testsb.append("BlackStapler");

        testsb.append("\n");
        testOut.write(testsb.toString());

        System.out.println("Img" + m + " " + svm.predict(testData));
      }
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(-1);
    }
  }