示例#1
0
 public static void cvt_YUVtoGRAY(Mat src, Mat dst) {
   /** convert YUV image to RGB then GRAY colorspace */
   mSrc = new Mat();
   src.copyTo(mSrc);
   Imgproc.cvtColor(mSrc, dst, Imgproc.COLOR_YUV420sp2RGB);
   Imgproc.cvtColor(dst, dst, Imgproc.COLOR_RGB2GRAY);
 }
  private static Bitmap canny(Bitmap image) {

    // convert image to matrix
    Mat Mat1 = new Mat(image.getWidth(), image.getHeight(), CvType.CV_32FC1);
    Utils.bitmapToMat(image, Mat1);

    // create temporary matrix2
    Mat Mat2 = new Mat(image.getWidth(), image.getHeight(), CvType.CV_32FC1);

    // convert image to grayscale
    Imgproc.cvtColor(Mat1, Mat2, Imgproc.COLOR_BGR2GRAY);

    // doing a gaussian blur prevents getting a lot of false hits
    Imgproc.GaussianBlur(Mat2, Mat1, new Size(3, 3), 2, 2); // ?

    // now apply canny function
    int param_threshold1 = 25; // manually defined
    int param_threshold2 = param_threshold1 * 3; // Cannys recommendation
    Imgproc.Canny(Mat1, Mat2, param_threshold1, param_threshold2);

    // ?
    Imgproc.cvtColor(Mat2, Mat1, Imgproc.COLOR_GRAY2BGRA, 4);

    // convert matrix to output bitmap
    Bitmap output = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.RGB_565);
    Utils.matToBitmap(Mat1, output);
    return output;
  }
示例#3
0
  public static Mat warp(Mat inputMat, Mat startM, int factor) {

    int resultWidth = 400 * factor;
    int resultHeight = 240 * factor;

    Mat outputMat = new Mat(resultWidth, resultHeight, CvType.CV_8UC4);

    Point ocvPOut1 = new Point(0, 0);
    Point ocvPOut2 = new Point(0, resultHeight);
    Point ocvPOut3 = new Point(resultWidth, resultHeight);
    Point ocvPOut4 = new Point(resultWidth, 0);
    List<Point> dest = new ArrayList<Point>();
    dest.add(ocvPOut1);
    dest.add(ocvPOut2);
    dest.add(ocvPOut3);
    dest.add(ocvPOut4);
    Mat endM = Converters.vector_Point2f_to_Mat(dest);

    Mat perspectiveTransform = Imgproc.getPerspectiveTransform(startM, endM);

    Imgproc.warpPerspective(
        inputMat,
        outputMat,
        perspectiveTransform,
        new Size(resultWidth, resultHeight),
        Imgproc.INTER_AREA);
    Imgproc.GaussianBlur(outputMat, outputMat, new org.opencv.core.Size(5, 5), 5);
    Imgproc.resize(outputMat, outputMat, new Size(resultWidth / factor, resultHeight / factor));

    Imgproc.threshold(outputMat, outputMat, 127, 255, Imgproc.THRESH_TOZERO);
    return outputMat;
  }
示例#4
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());
    }
  }
  /**
   * Finds and extracts all contours in the given Mat. Optionally also removes contours with areas
   * below that of MIN_CONTOUR_AREA.
   *
   * @param mask A mask of all resistors in the image
   * @param originalImage The original image from which the mask was created
   * @param thresholdByArea If true, remove contours below threshold
   * @return The list a found contours
   */
  private List<MatOfPoint> getContours(Mat mask, Mat originalImage, boolean thresholdByArea) {
    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Mat hierarchy = new Mat();
    Imgproc.findContours(
        mask,
        contours,
        hierarchy,
        Imgproc.RETR_EXTERNAL,
        Imgproc.CHAIN_APPROX_SIMPLE,
        new Point(0, 0));

    // remove any remaining noise by only keeping contours which area > threshold
    if (thresholdByArea) {
      for (int i = 0; i < contours.size(); i++) {
        double area = Imgproc.contourArea(contours.get(i));
        if (area < MIN_CONTOUR_AREA || area > 6000) {
          contours.remove(i);
          i--;
        }
      }
    }

    Mat drawing = Mat.zeros(originalImage.size(), CvType.CV_8U);

    for (int i = 0; i < contours.size(); i++) {
      Scalar color = new Scalar(255, 255, 255);
      Imgproc.drawContours(drawing, contours, i, color, 4, 8, hierarchy, 0, new Point());
    }
    paintBR(drawing);

    return contours;
  }
  /**
   * Locate rectangles in an image
   *
   * @param grayImage Grayscale image
   * @return Rectangle locations
   */
  public RectangleLocationResult locateRectangles(Mat grayImage) {
    Mat gray = grayImage.clone();

    // Filter out some noise
    Filter.downsample(gray, 2);
    Filter.upsample(gray, 2);

    Mat cacheHierarchy = new Mat();
    Mat grayTemp = new Mat();
    List<Rectangle> rectangles = new ArrayList<>();
    List<Contour> contours = new ArrayList<>();

    Imgproc.Canny(gray, grayTemp, 0, THRESHOLD_CANNY, APERTURE_CANNY, true);
    Filter.dilate(gray, 2);

    List<MatOfPoint> contoursTemp = new ArrayList<>();
    // Find contours - the parameters here are very important to compression and retention
    Imgproc.findContours(
        grayTemp, contoursTemp, cacheHierarchy, Imgproc.CV_RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

    // For each contour, test whether the contour is a rectangle
    // List<Contour> contours = new ArrayList<>();
    MatOfPoint2f approx = new MatOfPoint2f();
    for (MatOfPoint co : contoursTemp) {
      MatOfPoint2f matOfPoint2f = new MatOfPoint2f(co.toArray());
      Contour c = new Contour(co);

      // Attempt to fit the contour to the best polygon
      Imgproc.approxPolyDP(
          matOfPoint2f, approx, c.arcLength(true) * EPLISON_APPROX_TOLERANCE_FACTOR, true);

      Contour approxContour = new Contour(approx);

      // Make sure the contour is big enough, CLOSED (convex), and has exactly 4 points
      if (approx.toArray().length == 4
          && Math.abs(approxContour.area()) > 1000
          && approxContour.isClosed()) {

        // TODO contours and rectangles array may not match up, but why would they?
        contours.add(approxContour);

        // Check each angle to be approximately 90 degrees
        double maxCosine = 0;
        for (int j = 2; j < 5; j++) {
          double cosine =
              Math.abs(
                  MathUtil.angle(
                      approx.toArray()[j % 4], approx.toArray()[j - 2], approx.toArray()[j - 1]));
          maxCosine = Math.max(maxCosine, cosine);
        }

        if (maxCosine < MAX_COSINE_VALUE) {
          // Convert the points to a rectangle instance
          rectangles.add(new Rectangle(approx.toArray()));
        }
      }
    }

    return new RectangleLocationResult(contours, rectangles);
  }
  /**
   * @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;
  }
示例#8
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;
  }
  public Mat onCameraFrame(Mat inputFrame) {
    inputFrame.copyTo(mRgba);
    Point center = new Point(mRgba.width() / 2, mRgba.height() / 2);
    double angle = -90;
    double scale = 1.0;

    Mat mapMatrix = Imgproc.getRotationMatrix2D(center, angle, scale);
    Imgproc.warpAffine(mRgba, mGrayMat, mapMatrix, mRgba.size(), Imgproc.INTER_LINEAR);
    return mGrayMat;
  }
示例#10
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;
  }
  /**
   * @param source
   * @param size
   * @param delta
   * @return Mat
   */
  public static Mat Laplacian(Mat source, int size, int delta) {

    int ddepth = CvType.CV_16S;
    Mat abs_dst, dst;
    Imgproc.GaussianBlur(source, source, new Size(3.0, 3.0), 0);
    Imgproc.GaussianBlur(source, source, new Size(3, 3), 0, 0, Imgproc.BORDER_DEFAULT);
    // cvtColor( src, gray, CV_RGB2GRAY );
    /// Apply Laplace function
    Imgproc.Laplacian(source, source, CvType.CV_16S, size, 1, delta, Imgproc.BORDER_DEFAULT);
    return source;
  }
  /**
   * @param image
   * @param size
   * @return Mat
   */
  public static Mat cannyDetection(Mat image, int size) {

    Mat grayImage = new Mat();
    Mat detectedEdges = new Mat();
    // convert to grayscale
    Imgproc.cvtColor(image, grayImage, Imgproc.COLOR_BGR2GRAY);
    // reduce noise with a 3x3 kernel
    Imgproc.blur(grayImage, detectedEdges, new Size(3, 3));
    // canny detector, with ratio of lower:upper threshold of 3:1
    Imgproc.Canny(detectedEdges, detectedEdges, size, size / 3, 7, false);
    return detectedEdges;
  }
  private static Bitmap imgtrafo(
      Bitmap image1,
      Bitmap image2,
      int p1_x,
      int p1_y,
      int p2_x,
      int p2_y,
      int p3_x,
      int p3_y,
      int p4_x,
      int p4_y) {
    // set output size same size as input
    int resultWidth = image1.getWidth();
    int resultHeight = image1.getHeight();

    Mat inputMat = new Mat(image1.getWidth(), image1.getHeight(), CvType.CV_32FC1);
    Utils.bitmapToMat(image1, inputMat);
    Mat outputMat = new Mat(resultWidth, resultHeight, CvType.CV_32FC1);

    Point ocvPIn1 = new Point(p1_x, p1_y);
    Point ocvPIn2 = new Point(p2_x, p2_y);
    Point ocvPIn3 = new Point(p3_x, p3_y);
    Point ocvPIn4 = new Point(p4_x, p4_y);
    List<Point> source = new ArrayList<Point>();
    source.add(ocvPIn1);
    source.add(ocvPIn2);
    source.add(ocvPIn3);
    source.add(ocvPIn4);
    Mat inputQuad = Converters.vector_Point2f_to_Mat(source);

    Point ocvPOut1 = new Point(256, 40); // manually set
    Point ocvPOut2 = new Point(522, 62);
    Point ocvPOut3 = new Point(455, 479);
    Point ocvPOut4 = new Point(134, 404);
    List<Point> dest = new ArrayList<Point>();
    dest.add(ocvPOut1);
    dest.add(ocvPOut2);
    dest.add(ocvPOut3);
    dest.add(ocvPOut4);
    Mat outputQuad = Converters.vector_Point2f_to_Mat(dest);

    Mat perspectiveTransform = Imgproc.getPerspectiveTransform(inputQuad, outputQuad);

    Imgproc.warpPerspective(
        inputMat, outputMat, perspectiveTransform, new Size(resultWidth, resultHeight)); // ?

    Bitmap output = Bitmap.createBitmap(resultWidth, resultHeight, Bitmap.Config.RGB_565);
    Utils.matToBitmap(outputMat, output);
    return output;
  }
示例#14
0
  public boolean hasChanges(Mat current) {
    int PIXEL_DIFF_THRESHOLD = 5;
    int IMAGE_DIFF_THRESHOLD = 5;
    Mat bg = new Mat();
    Mat cg = new Mat();
    Mat diff = new Mat();
    Mat tdiff = new Mat();

    Imgproc.cvtColor(base, bg, Imgproc.COLOR_BGR2GRAY);
    Imgproc.cvtColor(current, cg, Imgproc.COLOR_BGR2GRAY);
    Core.absdiff(bg, cg, diff);
    Imgproc.threshold(diff, tdiff, PIXEL_DIFF_THRESHOLD, 0.0, Imgproc.THRESH_TOZERO);
    if (Core.countNonZero(tdiff) <= IMAGE_DIFF_THRESHOLD) {
      return false;
    }

    Imgproc.threshold(diff, diff, PIXEL_DIFF_THRESHOLD, 255, Imgproc.THRESH_BINARY);
    Imgproc.dilate(diff, diff, new Mat());
    Mat se = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(5, 5));
    Imgproc.morphologyEx(diff, diff, Imgproc.MORPH_CLOSE, se);

    List<MatOfPoint> points = new ArrayList<MatOfPoint>();
    Mat contours = new Mat();
    Imgproc.findContours(diff, points, contours, Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
    int n = 0;
    for (Mat pm : points) {
      log(lvl, "(%d) %s", n++, pm);
      printMatI(pm);
    }
    log(lvl, "contours: %s", contours);
    printMatI(contours);
    return true;
  }
示例#15
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;
    }
  }
  public Mat convertImageToBlackWhite(Mat imageMat, boolean applyGaussBlur) {
    Mat imageCloneMat = imageMat.clone();

    if (applyGaussBlur) {
      Imgproc.GaussianBlur(imageCloneMat, imageCloneMat, new Size(3, 3), 0, 0);
    }

    double thresh =
        Imgproc.threshold(
            imageCloneMat, imageCloneMat, 0, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU);

    Imgproc.threshold(imageCloneMat, imageCloneMat, thresh, 255, Imgproc.THRESH_BINARY_INV);

    return (imageCloneMat);
  }
 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;
 }
示例#18
0
  public void init_sd_imgs() {
    try {
      if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        File sdCardDir = Environment.getExternalStorageDirectory();
        String str_sd_dir = sdCardDir.getCanonicalPath();
        String str_path = str_sd_dir + "/andrcvs/";
        File dir = new File(str_path);
        Toast.makeText(MainActivity.this, str_path, Toast.LENGTH_LONG).show();

        if (!dir.exists()) {
          dir.mkdirs();
          for (int idx = 0; idx < res_imgs.length; idx++) {
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), res_imgs[idx]);
            Mat mat_rgb = new Mat();
            Utils.bitmapToMat(bmp, mat_rgb);
            String str_idx = String.format("%04d", idx + 1);
            String str_fn = str_path + "image_" + str_idx + ".jpg";
            Imgproc.cvtColor(mat_rgb, mat_rgb, Imgproc.COLOR_BGR2RGB);
            Imgcodecs.imwrite(str_fn, mat_rgb);
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#19
0
  @Override
  public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
    // Imgproc.bilateralFilter(inputFrame.gray(), inputFrame.rgba(), 9, 75, 75);

    /* if (captureBackground) {
        captureBackground = false;
        background = new Mat(inputFrame.gray(), new Rect(0, 0, inputFrame.gray().width(), inputFrame.gray().height()));
    }

    if (background == null) {
        return inputFrame.rgba();
    }


    return background;*/

    background = inputFrame.gray();

    Imgproc.cvtColor(background, mRgb, Imgproc.COLOR_GRAY2RGB);

    /*Imgproc.erode(mFGMask, mFGMask, new Mat());
    Imgproc.dilate(mFGMask, mFGMask, new Mat());

    Imgproc.findContours(mFGMask, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);
    Imgproc.drawContours(mRgb, contours, -1, new Scalar(255, 0, 0), 2);*/

    return mRgb;
  }
  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());
    }
  }
示例#21
0
  /**
   * Process the given Mat, finding, classifying and displaying all resistors present.
   *
   * @param originalImg The image to parse
   */
  private void parseImage(Mat originalImg) {
    Mat workingCopy = new Mat();
    originalImg.copyTo(workingCopy);

    // blur the original image to form resistor blobs. should remove white/silver/grey bands which
    // would otherwise
    // get picked up as part of the background, leads or shadows.
    Mat blurred = new Mat();
    // Imgproc.medianBlur(workingCopy, blurred, 29);
    Imgproc.blur(workingCopy, blurred, new Size(20, 20)); // faster

    // get a mask off the background
    Mat resistorMask = new Mat();
    generateResistorMask(blurred, Imgproc.THRESH_BINARY).copyTo(resistorMask);

    // find countours in mask
    List<MatOfPoint> contours = getContours(resistorMask, originalImg, true);

    // extract resistors in input image
    List<Resistor> resistors = extractResistorsFromContours(contours, originalImg, true);

    // segment and extract colour bands for each resistor
    extractColourBandsAndClassify(resistors, true);

    // calculate and display resistance value for each resistor based on classified colour bands
    calculateAndDisplayResistanceValues(resistors);
  }
示例#22
0
  private void createFigureBitmap() {
    if (mFigureBitmap != null) {
      mFigureBitmap.recycle();
    }
    // ビットマップ用意
    String targetPngFileUri = Camera72Utils.getTargetPngFileFullPath(mDirectory, mCurTarget);
    mFigureBitmap = BitmapFactory.decodeFile(targetPngFileUri, mOpt);
    // 抜き出しまだな場合
    if (mFigureBitmap == null) {
      Utils.showToast(mContext, R.string.not_extract_message);
      String targetJpgFileUri = Camera72Utils.getFgJpgFileFullPath(mDirectory, mCurTarget);
      mFigureBitmap = BitmapFactory.decodeFile(targetJpgFileUri, mOpt);
    }
    Log.i(TAG, "targetPngFile = " + targetPngFileUri);

    // OpenCV用オブジェクトを用意
    Mat mat = new Mat(mFigureBitmap.getHeight(), mFigureBitmap.getWidth(), CvType.CV_8UC4);
    org.opencv.android.Utils.bitmapToMat(mFigureBitmap, mat);

    // OpenCVで明るさ調整する
    Core.convertScaleAbs(mat, mat, mCvBrightScalar, 0);

    // OpenCVでぼかし調整する
    Imgproc.GaussianBlur(mat, mat, mCvGaussianSize, 0);

    // Bitmapに戻す
    org.opencv.android.Utils.matToBitmap(mat, mFigureBitmap);
  }
示例#23
0
    public void run() {
      do {
        synchronized (JavaCameraView.this) {
          try {
            JavaCameraView.this.wait();
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }

        if (!mStopThread) {
          switch (mPreviewFormat) {
            case Highgui.CV_CAP_ANDROID_COLOR_FRAME_RGBA:
              Imgproc.cvtColor(mBaseMat, mFrameChain[mChainIdx], Imgproc.COLOR_YUV2RGBA_NV21, 4);
              break;
            case Highgui.CV_CAP_ANDROID_GREY_FRAME:
              mFrameChain[mChainIdx] = mBaseMat.submat(0, mFrameHeight, 0, mFrameWidth);
              break;
            default:
              Log.e(TAG, "Invalid frame format! Only RGBA and Gray Scale are supported!");
          }
          ;
          if (!mFrameChain[mChainIdx].empty()) deliverAndDrawFrame(mFrameChain[mChainIdx]);
          mChainIdx = 1 - mChainIdx;
        }
      } while (!mStopThread);
      Log.d(TAG, "Finish processing thread");
    }
示例#24
0
  public MarkerTracker(Mat image, Mat template) {
    this.image = image;
    this.template = template;
    Log.i("Marker-Tracker", "image is null?::" + (null == image));

    imgGray = new Mat(image.size(), image.type());
    templGray = new Mat(template.size(), template.type());
    // Convert them to grayscale
    Imgproc.cvtColor(image, imgGray, Imgproc.COLOR_BGRA2GRAY);
    //  Core.normalize(imgGray, imgGray, 0, 255, Core.NORM_MINMAX);

    // Mat	grayImage02 = new Mat(image02.rows(), image02.cols(), image02.type());
    Imgproc.cvtColor(template, templGray, Imgproc.COLOR_BGRA2GRAY);
    //        Core.normalize(templGray, templGray, 0, 255, Core.NORM_MINMAX);

  }
  private Scalar converScalarHsv2Rgba(Scalar hsvColor) {
    Mat pointMatRgba = new Mat();
    Mat pointMatHsv = new Mat(1, 1, CvType.CV_8UC3, hsvColor);
    Imgproc.cvtColor(pointMatHsv, pointMatRgba, Imgproc.COLOR_HSV2RGB_FULL, 4);

    return new Scalar(pointMatRgba.get(0, 0));
  }
示例#26
0
    @Override
    protected Void doInBackground(Void... params) {
      publishProgress(0);
      Mat hsvImg = heatmap(data, progressDialog);
      Mat finishedImage = new Mat();
      Imgproc.cvtColor(hsvImg, finishedImage, Imgproc.COLOR_HSV2BGR);

      File mediaStorageDir =
          new File(Environment.getExternalStorageDirectory().getPath(), "images/Colored_Images");

      if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
          Log.e(TAG, "failed to create directory");
          return null;
        }
      }

      String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
      Log.v(
          TAG,
          "SAVING: " + mediaStorageDir.getPath() + File.separator + "scan_" + timeStamp + ".jpg");
      Highgui.imwrite(
          mediaStorageDir.getPath() + File.separator + "scan_" + timeStamp + ".jpg", finishedImage);

      return null;
    }
  public void setHsvColor(Scalar hsvColor) {
    double minH =
        (hsvColor.val[0] >= mColorRadius.val[0]) ? hsvColor.val[0] - mColorRadius.val[0] : 0;
    double maxH =
        (hsvColor.val[0] + mColorRadius.val[0] <= 255)
            ? hsvColor.val[0] + mColorRadius.val[0]
            : 255;

    mLowerBound.val[0] = minH;
    mUpperBound.val[0] = maxH;

    mLowerBound.val[1] = hsvColor.val[1] - mColorRadius.val[1];
    mUpperBound.val[1] = hsvColor.val[1] + mColorRadius.val[1];

    mLowerBound.val[2] = hsvColor.val[2] - mColorRadius.val[2];
    mUpperBound.val[2] = hsvColor.val[2] + mColorRadius.val[2];

    mLowerBound.val[3] = 0;
    mUpperBound.val[3] = 255;

    Mat spectrumHsv = new Mat(1, (int) (maxH - minH), CvType.CV_8UC3);

    for (int j = 0; j < maxH - minH; j++) {
      byte[] tmp = {(byte) (minH + j), (byte) 255, (byte) 255};
      spectrumHsv.put(0, j, tmp);
    }

    Imgproc.cvtColor(spectrumHsv, mSpectrum, Imgproc.COLOR_HSV2RGB_FULL, 4);
  }
示例#28
0
 public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
   frame = inputFrame.rgba();
   outputFrame = frame.clone();
   if (homography != null) {
     if (markerValue != -1 && markerValue != oldMarkerValue) {
       oldMarkerValue = markerValue;
       outputLogo = logo.clone();
       Core.putText(
           outputLogo,
           Integer.toString(markerValue),
           new Point(5, 505),
           Core.FONT_HERSHEY_SIMPLEX,
           5,
           new Scalar(255, 0, 0),
           5);
     }
     Imgproc.warpPerspective(
         outputLogo,
         outputFrame,
         homography,
         new Size(WIDTH, HEIGHT),
         Imgproc.INTER_NEAREST,
         Imgproc.BORDER_TRANSPARENT,
         new Scalar(0));
   }
   return outputFrame;
 }
  @Override
  public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {

    mRgba = inputFrame.rgba();
    Imgproc.cvtColor(mRgba, grayScaleImage, Imgproc.COLOR_RGBA2RGB);

    MatOfRect faces = new MatOfRect();

    // detect faces
    if (cascadeClassifier != null) {
      cascadeClassifier.detectMultiScale(
          grayScaleImage,
          faces,
          1.1,
          2,
          2,
          new Size(absoluteFaceSize, absoluteFaceSize),
          new Size());
    }

    Rect[] facesArray = faces.toArray();
    for (int i = 0; i < facesArray.length; i++)
      Core.rectangle(mRgba, facesArray[i].tl(), facesArray[i].br(), new Scalar(0, 255, 0, 255), 3);

    if (facesArray.length > 0) {
      facesInASecond.add(true);
    } else {
      facesInASecond.add(false);
    }

    return mRgba;
  }
  /**
   * @param source
   * @param delta
   * @return Mat
   */
  public static Mat Sobel(Mat source, int delta) {

    Mat grey = new Mat();
    Imgproc.cvtColor(source, grey, Imgproc.COLOR_BGR2GRAY);
    Mat sobelx = new Mat();
    Imgproc.Sobel(grey, sobelx, CvType.CV_32F, 1, delta);

    double minVal, maxVal;
    Core.MinMaxLocResult minMaxLocResult = Core.minMaxLoc(sobelx);
    minVal = minMaxLocResult.minVal;
    maxVal = minMaxLocResult.maxVal;

    Mat draw = new Mat();
    sobelx.convertTo(
        draw, CvType.CV_8U, 255.0 / (maxVal - minVal), -minVal * 255.0 / (maxVal - minVal));
    return draw;
  }