Ejemplo n.º 1
0
  /**
   * @param inputImg
   * @return Mat
   */
  public static Mat watershed(Mat inputImg) {

    Mat target = new Mat(inputImg.rows(), inputImg.cols(), CvType.CV_8UC3);
    Imgproc.cvtColor(inputImg, target, Imgproc.COLOR_BGR2RGB);

    // Conversion to 8UC1 grayscale image
    Mat grayScale = new Mat(inputImg.rows(), inputImg.cols(), CvType.CV_32SC1);
    Imgproc.cvtColor(inputImg, grayScale, Imgproc.COLOR_BGR2GRAY);

    // constructing a 3x3 kernel for morphological opening
    Mat openingKernel = Mat.ones(9, 9, CvType.CV_8U);

    // яскравість
    // target.convertTo(target, -1, 10d * 12 / 100, 0);
    // Imgproc.dilate(target, target, new Mat(), new Point(-1, -1), 1);

    Size s = new Size(27, 27);
    Imgproc.GaussianBlur(target, target, s, 1.7);

    Imgproc.morphologyEx(target, target, Imgproc.MORPH_OPEN, openingKernel);

    // dilation operation for extracting the background
    // Imgproc.dilate(target, target, openingKernel);
    // Imgproc.erode(target, target, new Mat(), new Point(-1, -1), 1);

    Mat seeds = new Mat(target.rows(), target.cols(), CvType.CV_32SC1);

    for (int i = 0; i < 10; i++) {
      seeds.put(((int) Math.random()) % target.rows(), ((int) Math.random()) % target.cols(), i);
    }

    Imgproc.watershed(target, seeds);
    // Imgproc.threshold(target,target, 50, 155, Imgproc.THRESH_BINARY );
    return target;
  }
Ejemplo n.º 2
0
  private Mat rotateImage(Mat src, double angle) {
    Point center = new Point(src.cols() / 2, src.rows() / 2);
    double scale = 1.0;

    Mat rotateMat = Imgproc.getRotationMatrix2D(center, angle, scale);
    Mat dst = new Mat();
    Size frameSize = new Size(src.rows(), src.cols());

    // adjust dst center point
    double m[] = new double[6];
    rotateMat.get(0, 0, m);
    m[2] += (frameSize.width - src.cols()) / 2;
    m[5] += (frameSize.height - src.rows()) / 2;
    rotateMat.put(0, 0, m);

    Imgproc.warpAffine(
        src,
        dst,
        rotateMat,
        frameSize,
        Imgproc.INTER_LINEAR,
        Imgproc.BORDER_CONSTANT,
        Scalar.all(0));

    return dst;
  }
Ejemplo n.º 3
0
  public static void main(String[] args) {
    try {
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

      File input = new File("traffic_signal.jpg");
      BufferedImage image = ImageIO.read(input);

      byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
      Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3);
      mat.put(0, 0, data);

      Mat mat1 = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC1);
      Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2GRAY);

      byte[] data1 = new byte[mat1.rows() * mat1.cols() * (int) (mat1.elemSize())];
      mat1.get(0, 0, data1);
      BufferedImage image1 =
          new BufferedImage(mat1.cols(), mat1.rows(), BufferedImage.TYPE_BYTE_GRAY);
      image1.getRaster().setDataElements(0, 0, mat1.cols(), mat1.rows(), data1);

      File ouptut = new File("output\\grayscale_" + new Date().getTime() + ".jpg");
      ImageIO.write(image1, "jpg", ouptut);
    } catch (Exception e) {
      System.out.println("Error: " + e.getMessage());
    }
  }
Ejemplo n.º 4
0
  /**
   * Rotate a Mat by the specified degree
   *
   * @param src The source Mat
   * @param angle The angle by which to rotate by
   * @return The rotated Mat
   */
  public static Mat rotate(Mat src, double angle) {
    int len = src.cols() > src.rows() ? src.cols() : src.rows();
    Point pt = new Point(len / 2.0, len / 2.0);
    Mat r = Imgproc.getRotationMatrix2D(pt, angle, 1.0);
    Mat dst = new Mat();

    Imgproc.warpAffine(src, dst, r, new Size(len, len));

    return dst;
  }
 public static Image convertMatToImage(Mat m) {
   int type = BufferedImage.TYPE_BYTE_GRAY;
   if (m.channels() > 1) {
     type = BufferedImage.TYPE_3BYTE_BGR;
   }
   int bufferSize = m.channels() * m.cols() * m.rows();
   byte[] b = new byte[bufferSize];
   m.get(0, 0, b);
   BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
   final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
   System.arraycopy(b, 0, targetPixels, 0, b.length);
   return image;
 }
Ejemplo n.º 6
0
  /** Capture images and run color processing through here */
  public void capture() {
    VideoCapture camera = new VideoCapture();

    camera.set(12, -20); // change contrast, might not be necessary

    // CaptureImage image = new CaptureImage();

    camera.open(0); // Useless
    if (!camera.isOpened()) {
      System.out.println("Camera Error");

      // Determine whether to use System.exit(0) or return

    } else {
      System.out.println("Camera OK");
    }

    boolean success = camera.read(capturedFrame);
    if (success) {
      try {
        processWithContours(capturedFrame, processedFrame);
      } catch (Exception e) {
        System.out.println(e);
      }
      // image.processFrame(capturedFrame, processedFrame);
      // processedFrame should be CV_8UC3

      // image.findCaptured(processedFrame);

      // image.determineKings(capturedFrame);

      int bufferSize = processedFrame.channels() * processedFrame.cols() * processedFrame.rows();
      byte[] b = new byte[bufferSize];

      processedFrame.get(0, 0, b); // get all the pixels
      // This might need to be BufferedImage.TYPE_INT_ARGB
      img =
          new BufferedImage(
              processedFrame.cols(), processedFrame.rows(), BufferedImage.TYPE_INT_RGB);
      int width = (int) camera.get(Highgui.CV_CAP_PROP_FRAME_WIDTH);
      int height = (int) camera.get(Highgui.CV_CAP_PROP_FRAME_HEIGHT);
      // img.getRaster().setDataElements(0, 0, width, height, b);
      byte[] a = new byte[bufferSize];
      System.arraycopy(b, 0, a, 0, bufferSize);

      Highgui.imwrite("camera.jpg", processedFrame);
      System.out.println("Success");
    } else System.out.println("Unable to capture image");

    camera.release();
  }
Ejemplo n.º 7
0
  private double match_eye(Rect area, Mat mTemplate, int type) {
    Point matchLoc;
    Mat mROI = mGray.submat(area);
    int result_cols = mGray.cols() - mTemplate.cols() + 1;
    int result_rows = mGray.rows() - mTemplate.rows() + 1;
    if (mTemplate.cols() == 0 || mTemplate.rows() == 0) {
      return 0.0;
    }
    mResult = new Mat(result_cols, result_rows, CvType.CV_32FC1);

    switch (type) {
      case TM_SQDIFF:
        Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_SQDIFF);
        break;
      case TM_SQDIFF_NORMED:
        Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_SQDIFF_NORMED);
        break;
      case TM_CCOEFF:
        Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_CCOEFF);
        break;
      case TM_CCOEFF_NORMED:
        Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_CCOEFF_NORMED);
        break;
      case TM_CCORR:
        Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_CCORR);
        break;
      case TM_CCORR_NORMED:
        Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_CCORR_NORMED);
        break;
    }

    Core.MinMaxLocResult mmres = Core.minMaxLoc(mResult);

    if (type == TM_SQDIFF || type == TM_SQDIFF_NORMED) {
      matchLoc = mmres.minLoc;
    } else {
      matchLoc = mmres.maxLoc;
    }

    Point matchLoc_tx = new Point(matchLoc.x + area.x, matchLoc.y + area.y);
    Point matchLoc_ty =
        new Point(matchLoc.x + mTemplate.cols() + area.x, matchLoc.y + mTemplate.rows() + area.y);

    Core.rectangle(mRgba, matchLoc_tx, matchLoc_ty, new Scalar(255, 255, 0, 255));

    if (type == TM_SQDIFF || type == TM_SQDIFF_NORMED) {
      return mmres.maxVal;
    } else {
      return mmres.minVal;
    }
  }
  public void copyMat(Mat src, Mat dest) {
    int srcRows = src.rows();
    int srcCols = src.cols();
    int destRows = dest.rows();
    int destCols = dest.cols();

    for (int i = 0; i < srcRows; i++) {
      for (int j = 0; j < srcCols; j++) {
        double bit = src.get(i, j)[0];
        dest.put(i, j, bit);
        System.out.println(bit);
      }
    }
  }
Ejemplo n.º 9
0
  public void processFrame(CameraEvents.Frame frameEvent) {
    if (service.getActivityMode() != ActivityEvent.Mode.WARP) return;
    if (mode == Mode.SAMPLEWARPPLANE || mode == Mode.SAMPLEWARPGLASS) {
      synchronized (this) {
        if (!isSetup) setupMatrices();
        if (captureSample) {
          captureSample = false;
          Log.d(TAG, "Warp: Capturing Sample");
          Mat frame = frameEvent.getCameraFrame().getRGB();
          byte[] frameJPEG = frameEvent.getCameraFrame().getJPEG();
          if (sampleBGR == null
              || sampleBGR.height() != frame.height()
              || sampleBGR.width() != frame.width())
            sampleBGR = new Mat(frame.rows(), frame.cols(), CvType.CV_8UC3);
          Imgproc.cvtColor(frame, sampleBGR, Imgproc.COLOR_RGB2BGR);
          useSample = true;
          // TODO: Specialize it for this group/device
          com.dappervision.wearscript.Utils.eventBusPost(
              new SendEvent("warpsample", "", ValueFactory.createRawValue(frameJPEG)));
        }
      }
    }

    if (busy) return;
    synchronized (this) {
      busy = true;
      if (!isSetup) setupMatrices();
      if (mode == Mode.CAM2GLASS) {
        Mat inputBGR;
        Mat frame = frameEvent.getCameraFrame().getRGB();
        if (frameBGR == null
            || frameBGR.height() != frame.height()
            || frameBGR.width() != frame.width())
          frameBGR = new Mat(frame.rows(), frame.cols(), CvType.CV_8UC3);
        Mat hSmallToGlassMat = getHSmallToGlassMat(frame.rows(), frame.cols());
        if (hSmallToGlassMat == null) {
          Log.w(TAG, "Warp: Bad size");
          busy = false;
          return;
        }
        Imgproc.cvtColor(frame, frameBGR, Imgproc.COLOR_RGB2BGR);
        inputBGR = frameBGR;
        Imgproc.warpPerspective(
            inputBGR, frameWarp, hSmallToGlassMat, new Size(frameWarp.width(), frameWarp.height()));
        drawFrame(frameWarp);
      }
      busy = false;
    }
  }
Ejemplo n.º 10
0
  public static boolean checkAngleL(Mat binary) {
    int leftPointX = -1;

    double pixel[];

    for (int i = 0; i < binary.cols(); i++) {
      pixel = binary.get(0, i);
      if (pixel[0] != 0.0) {
        leftPointX = i;
      }
    }

    int rightPointY = -1;
    for (int i = 0; i < binary.rows(); i++) {
      pixel = binary.get(i, binary.cols() - 1);
      if (pixel[0] != 0.0) {
        rightPointY = i;
        break;
      }
    }

    double opposite = rightPointY;
    double adjacent = binary.cols() - 1 - leftPointX;

    double angle = Math.atan2(opposite, adjacent) * (180 / Math.PI);

    if (angle >= 50.0 & angle < 70.0) {
      return true; // angle indicates L
    } else {
      return false; // angle indicates not L
    }
  }
 private void displayMarkersDebug(Mat imgMat, Scalar contourColor, Scalar codesColor) {
   ArrayList<MatOfPoint> components = new ArrayList<MatOfPoint>();
   Mat hierarchy = new Mat();
   DtouchMarker marker = new DtouchMarker();
   boolean markerFound = findMarkers(imgMat, marker, components, hierarchy);
   if (markerFound) {
     String code = codeArrayToString(marker.getCode());
     Point codeLocation = new Point(imgMat.cols() / 4, imgMat.rows() / 8);
     Core.putText(mRgba, code, codeLocation, Core.FONT_HERSHEY_COMPLEX, 1, codesColor, 3);
     Imgproc.drawContours(
         mRgba,
         components,
         marker.getComponentIndex(),
         contourColor,
         3,
         8,
         hierarchy,
         2,
         new Point(0, 0));
   }
   if (components != null) components.clear();
   if (hierarchy != null) hierarchy.release();
   components = null;
   hierarchy = null;
 }
  /**
   * Returns square area for image segment.
   *
   * @param imgMat Source image from which to compute image segment.
   * @return square area which contains image segment.
   */
  private Rect calculateImageSegmentArea(Mat imgMat) {
    int width = imgMat.cols();
    int height = imgMat.rows();
    double aspectRatio = (double) width / (double) height;

    int imgWidth = width / 2;
    int imgHeight = height / 2;

    // Size of width and height varies of input image can vary. Make the image segment width and
    // height equal in order to make
    // the image segment square.

    // if width is more than the height.
    if (aspectRatio > 1) {
      // if total height is greater than imgWidth.
      if (height > imgWidth) imgHeight = imgWidth;
    } else if (aspectRatio < 1) { // height is more than the width.
      // if total width is greater than the imgHeight.
      if (width > imgHeight) imgWidth = imgHeight;
    }

    // find the centre position in the source image.
    int x = (width - imgWidth) / 2;
    int y = (height - imgHeight) / 2;

    return new Rect(x, y, imgWidth, imgHeight);
  }
Ejemplo n.º 13
0
  public static void main(String[] args) {
    try {

      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
      Mat source = Imgcodecs.imread("test_image.jpg", 0);

      Mat destination = new Mat(source.rows(), source.cols(), source.type());
      Imgproc.GaussianBlur(source, source, new Size(45, 45), 0);
      Imgproc.adaptiveThreshold(
          source, source, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 75, 10);
      Core.bitwise_not(source, source);

      // Line detection
      Mat img2 = null;
      Imgproc.cvtColor(source, img2, Imgproc.COLOR_GRAY2RGB);

      Mat img3 = null;
      Imgproc.cvtColor(source, img3, Imgproc.COLOR_GRAY2RGB);

      MatOfInt4 lines = new MatOfInt4();
      // Imgproc.HoughLines(img, lines, rho, theta, threshold);

      // Write to File
      Imgcodecs.imwrite("gaussian.jpg", source);
      System.out.println("Success!");
    } catch (Exception e) {
      System.out.println("Error has occurred: " + e.getMessage());
    }
  }
Ejemplo n.º 14
0
  /**
   * Helper function to convert a Mat into a BufferedImage. Taken from
   * http://answers.opencv.org/question/10344/opencv-java-load-image-to-gui Author: 'Lucky Luke'
   *
   * @param matrix Mat of type CV_8UC3 or CV_8UC1
   * @return BufferedImage of type TYPE_3BYTE_BGR or TYPE_BYTE_GRAY
   */
  private static BufferedImage matToBufferedImage(Mat matrix) {
    int cols = matrix.cols();
    int rows = matrix.rows();
    int elemSize = (int) matrix.elemSize();
    byte[] data = new byte[cols * rows * elemSize];
    int type;

    matrix.get(0, 0, data);

    switch (matrix.channels()) {
      case 1:
        type = BufferedImage.TYPE_BYTE_GRAY;
        break;

      case 3:
        type = BufferedImage.TYPE_3BYTE_BGR;

        // bgr to rgb
        byte b;
        for (int i = 0; i < data.length; i = i + 3) {
          b = data[i];
          data[i] = data[i + 2];
          data[i + 2] = b;
        }
        break;

      default:
        return null;
    }

    BufferedImage image = new BufferedImage(cols, rows, type);
    image.getRaster().setDataElements(0, 0, cols, rows, data);

    return image;
  }
Ejemplo n.º 15
0
  /**
   * Order the detected bands into band 1, band 2 and the multiplier. The farthest band from the
   * center of the resistor Mat will always be band 1.
   *
   * <p>Band contours are created from top left to bottom right of the image. Therefore unless
   * resistor is perfectly horizontal, the middle band will always be 2nd, and the order just needs
   * to be flipped if necessary
   */
  public void orderBands() {

    // Calculate the center of the resistor image.
    Point resistorImageCenter = new Point(resistorMat.cols() / 2, resistorMat.rows() / 2);

    double farthestDist = 0;
    int band1Idx = 0;

    // find the band farthest from the center.
    for (int i = 0; i < bands.size(); i++) {
      ColourBand cb = bands.get(i);
      double dist = euclidDist(resistorImageCenter, cb.center);
      if (dist > farthestDist) {
        farthestDist = dist;
        band1Idx = i;
      }
    }

    // assume bands are already in the correct order band1Idx == 0
    orderedBands = bands;

    // if bands are in reverse order, reverse the array to get the ordered bands
    if (band1Idx == 2) {
      java.util.Collections.reverse(orderedBands);
    }
  }
Ejemplo n.º 16
0
 @Override
 public void OnKeypointsFoundForOther(Mat image) {
   Bitmap disp =
       Bitmap.createBitmap(
           image.cols(), image.rows(), Bitmap.Config.ARGB_8888); // Android uses ARGB_8888
   Utils.matToBitmap(image, disp);
   mImageAdapter.setOtherKeyPointImage(disp);
 }
Ejemplo n.º 17
0
 private static void printMatI(Mat mat) {
   int[] data = new int[mat.channels()];
   for (int r = 0; r < mat.rows(); r++) {
     for (int c = 0; c < mat.cols(); c++) {
       mat.get(r, c, data);
       log(lvl, "(%d, %d) %s", r, c, Arrays.toString(data));
     }
   }
 }
Ejemplo n.º 18
0
 public static BufferedImage bufferedImage(Mat m) {
   int type = BufferedImage.TYPE_BYTE_GRAY;
   if (m.channels() > 1) {
     type = BufferedImage.TYPE_3BYTE_BGR;
   }
   BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
   m.get(
       0, 0, ((DataBufferByte) image.getRaster().getDataBuffer()).getData()); // get all the pixels
   return image;
 }
Ejemplo n.º 19
0
  private Point getUniformCoordinates(double angle, double dist) {

    ////////////   BURADA MARGIN 1.0 DONDURMELI
    Point uv = new Point();
    uv.x = (angle / 360);
    // uv.y = (dist/(halfGenImageSize));
    uv.y = (dist * scale + offset) / srcImage.rows();

    return uv;
  }
Ejemplo n.º 20
0
  private void CreateAuxiliaryMats() {
    if (mGray.empty()) return;

    int rows = mGray.rows();
    int cols = mGray.cols();

    if (mZoomWindow == null) {
      mZoomWindow = mRgba.submat(rows / 2 + rows / 10, rows, cols / 2 + cols / 10, cols);
      mZoomWindow2 = mRgba.submat(0, rows / 2 - rows / 10, cols / 2 + cols / 10, cols);
    }
  }
Ejemplo n.º 21
0
 private Mat buildROI(Mat src) {
   int offset = mZoomImg.getWidth();
   int rows = src.rows();
   int cols = src.cols();
   Mat sub =
       src.submat(
           rows / 2 - offset / 2,
           rows / 2 + offset / 2,
           cols / 2 - offset / 2,
           cols / 2 + offset / 2);
   return sub;
 }
Ejemplo n.º 22
0
  public static void draw_opticflow(Mat flow, Mat cflowmap, int step, Scalar color) {
    int i = 0, j = 0;
    for (int y = 0; y < cflowmap.rows(); y += step) {
      for (int x = 0; x < cflowmap.cols(); x += step) {

        double[] fxy = Sample1View.flow.get(50, 50);

        // for testing, getting change in values sa frames at point 50,50
        // result : fxy ng.change ang value, however, kun i.add na ang 50, mura xag ma.zero??
        i = (int) Math.round(fxy[0]);
        j = (int) (50.00 + fxy[1]);

        Core.putText(
            cflowmap,
            Double.toString(j),
            new Point(10, 100),
            3 /* CV_FONT_HERSHEY_COMPLEX */,
            2,
            new Scalar(255, 0, 0, 255),
            3);

        // Core.line(cflowmap, new Point(x,y), new Point(i,j), new Scalar(0,0,255), 4);
        // Core.circle(cflowmap, new Point(i,j), 2, new Scalar(0,0,255), -1);
        // Core.circle(cflowmap, new Point(x,y), 2, color, -1);
        // System.out.print("fxy"+i+" "+j+"\n");

        // Core.circle(cflowmap, new Point(cflowmap.width(), 50), 5, new Scalar(255,255,255), -1);
        if (i < (cflowmap.width() / 2) && i != 0.0) {
          Core.circle(cflowmap, new Point(i, j), 2, new Scalar(0, 0, 255), -1);
          Core.putText(
              cflowmap,
              "LEFT",
              new Point(10, 100),
              3 /* CV_FONT_HERSHEY_COMPLEX */,
              2,
              new Scalar(255, 255, 255, 255),
              3);

        } else if (i > (cflowmap.width() / 2) && i != x) {
          Core.circle(cflowmap, new Point(i, j), 2, new Scalar(0, 0, 255), -1);
          Core.putText(
              cflowmap,
              "RIGHT",
              new Point(10, 100),
              3 /* CV_FONT_HERSHEY_COMPLEX */,
              2,
              new Scalar(255, 255, 255, 255),
              3);
        }
      }
    }
  }
Ejemplo n.º 23
0
 public Bitmap convertMatToBitmap(Mat seedsImage) {
   Bitmap bmp = null;
   Mat tmp = new Mat(seedsImage.height(), seedsImage.width(), CvType.CV_8U, new Scalar(4));
   try {
     // Imgproc.cvtColor(seedsImage, tmp, Imgproc.COLOR_RGB2BGRA);
     Imgproc.cvtColor(seedsImage, tmp, Imgproc.COLOR_GRAY2RGBA, 4);
     bmp = Bitmap.createBitmap(tmp.cols(), tmp.rows(), Bitmap.Config.ARGB_8888);
     Utils.matToBitmap(tmp, bmp);
   } catch (CvException e) {
     Log.d("Exception", e.getMessage());
   }
   return bmp;
 }
  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);
  }
  public Mat onCameraFrame(CvCameraViewFrame inputFrame) {

    mRgba = inputFrame.rgba();

    mGray = inputFrame.gray();

    if (!detectionInProgress) {
      Mat image = new Mat(mGray.rows(), mGray.cols(), mGray.type());
      mGray.copyTo(image);
      detectFaceOnFrame(image);
    }

    return mRgba;
  }
Ejemplo n.º 26
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;
 }
Ejemplo n.º 27
0
  @Override
  public void OnHomographyStored(TransformInfo storage) {
    // Draw the key point matches and put in gallery
    Mat matches = storage.getMatchImage();
    // Must convert to Bitmap from Mat
    Bitmap disp =
        Bitmap.createBitmap(
            matches.cols(), matches.rows(), Bitmap.Config.ARGB_8888); // Android uses ARGB_8888
    Utils.matToBitmap(matches, disp);
    mImageAdapter.setPutativeImageWithLinesImage(disp);

    // Ready to show display reset text
    mExpandedImageText.setText(R.string.show_exp_image);
    boolean ready = mCVLibraryInitialized;
    transformButton.setEnabled(ready);
  }
  private Bitmap displayDetectedMarker(VideoCapture capture, Mat markerImage) {
    // Get original image.
    capture.retrieve(mRgba, Highgui.CV_CAP_ANDROID_COLOR_FRAME_RGBA);
    displayRectOnImageSegment(mRgba, true);
    displayMarkerImage(mMarkerImage, mRgba);

    Bitmap bmp = Bitmap.createBitmap(mRgba.cols(), mRgba.rows(), Bitmap.Config.ARGB_8888);
    try {
      Utils.matToBitmap(mRgba, bmp);
      return bmp;
    } catch (Exception e) {
      Log.e("TWMarkerSurfaceView", "Utils.matToBitmap() throws an exception: " + e.getMessage());
      bmp.recycle();
      return null;
    }
  }
  public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    mRgba = inputFrame.rgba();

    if (mIsColorSelected) {
      abc = mDetector.process(mRgba);
      // hehe.setText(abc.toString());
      List<MatOfPoint> contours = mDetector.getContours();
      Log.e(TAG, "Contours count: " + contours.size());
      Imgproc.drawContours(mRgba, contours, -1, CONTOUR_COLOR);

      Mat colorLabel = mRgba.submat(4, 68, 4, 68);
      colorLabel.setTo(mBlobColorRgba);

      Mat spectrumLabel = mRgba.submat(4, 4 + mSpectrum.rows(), 70, 70 + mSpectrum.cols());
      mSpectrum.copyTo(spectrumLabel);
    }

    return mRgba;
  }
Ejemplo n.º 30
0
  private void prepareSpherify(Bitmap bitmap) {

    int insideCircleOutRadius;
    int topY, footY, withinHeight;

    if (!OpenCVLoader.initDebug()) {
      // Handle initialization error
      AppFunctions.showToast(activity.getApplicationContext(), "OpenGL initialization error!");
      activity.finish();
    }

    if (srcImage == null) {
      srcImage = new Mat();

      srcImage.create(bitmap.getHeight(), bitmap.getWidth(), CvType.CV_8UC3);
      Bitmap myBitmap32 = bitmap.copy(Bitmap.Config.ARGB_8888, true);
      Utils.bitmapToMat(myBitmap32, srcImage);

      Imgproc.cvtColor(srcImage, srcImage, Imgproc.COLOR_BGR2RGB, 4);
    }

    Utils.bitmapToMat(bitmap, srcImage);
    // cropImage();
    seamlessEdges(srcImage);
    mSrcWidth = srcImage.cols();
    mSrcHeight = srcImage.rows();

    halfGenImageSize = genImageSize / 2;
    spherifiedImage = new Mat();
    spherifiedImage.create(genImageSize, genImageSize, CvType.CV_8UC4);

    insideCircleOutRadius = (int) (genImageSize / 12);

    topY = (int) (mSrcHeight * (topMargin));
    footY = (int) (mSrcHeight * (footMargin));
    withinHeight = topY - footY;
    scale = withinHeight / ((double) (croppedImageSize / 2 - insideCircleOutRadius));
    offset = (int) (footY - scale * insideCircleOutRadius);
    numProcesses = Runtime.getRuntime().availableProcessors();
    if (numProcesses < 3) numProcesses = 1;
    else numProcesses = 3;
  }