List of usage examples for org.opencv.core Scalar Scalar
public Scalar(double v0, double v1, double v2)
From source file:opencvtesting.OpenCVTesting.java
/** * @param args the command line arguments *//*from w w w . j av a 2 s. c o m*/ public static void main(String[] args) throws IOException { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(CameraWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CameraWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CameraWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CameraWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ CameraWindow cWindow = new CameraWindow(); cWindow.setVisible(true); Random gen = new Random(); JFrame frameF = new JFrame(); System.loadLibrary("opencv_java248"); VideoCapture camera = new VideoCapture(0); camera.open(0); //Useless if (!camera.isOpened()) { System.out.println("Camera Error"); } else { System.out.println("Camera OK?"); } frame = new Mat(); frame_gray = new Mat(); camera.read(frame); showResult(frame, frameF); dst = new Mat(frame.size(), frame.type()); mapX = new Mat(frame.size(), CvType.CV_32FC1); mapY = new Mat(frame.size(), CvType.CV_32FC1); boolean bEnd = true; while (bEnd) { camera.read(frame); Imgproc.cvtColor(frame, frame_gray, Imgproc.COLOR_BGR2GRAY); Imgproc.GaussianBlur(frame_gray, frame_gray, new Size(1, 1), 2); Imgproc.equalizeHist(frame_gray, frame_gray); Mat circles = new Mat(); Imgproc.HoughCircles(frame_gray, circles, Imgproc.CV_HOUGH_GRADIENT, cWindow.get_dp(), frame_gray.rows() / 8, cWindow.get_param1(), cWindow.get_param2(), 0, 0); //System.out.println(circles.rows()); for (int i = 0; i < circles.cols(); i++) { double[] circle = circles.get(0, i); Point center = new Point(Math.round(circle[0]), Math.round(circle[1])); int radius = (int) Math.round(circle[2]); Core.circle(frame, center, 3, new Scalar(gen.nextInt(), gen.nextInt(), gen.nextInt()), -1, 8, 0); Core.circle(frame, center, radius, new Scalar(gen.nextInt(), gen.nextInt(), gen.nextInt()), 3, 8, 0); } showResult(frame, frameF); } //Highgui.imwrite("camera1.jpg", frame); //System.out.println("OK"); }
From source file:org.akvo.caddisfly.sensor.colorimetry.strip.ui.ResultActivity.java
License:Open Source License
@Override public void showResults() { resultImageUrl = UUID.randomUUID().toString() + ".png"; Intent intent = getIntent();//from w w w . j av a2s. c om String uuid = intent.getStringExtra(Constant.UUID); Mat strip; StripTest stripTest = new StripTest(); // get information on the strip test from JSON StripTest.Brand brand = stripTest.getBrand(uuid); // for display purposes sort the patches by position on the strip List<StripTest.Brand.Patch> patches = brand.getPatchesSortedByPosition(); // get the JSON describing the images of the patches that were stored before JSONArray imagePatchArray = null; try { String json = FileUtil.readFromInternalStorage(this, Constant.IMAGE_PATCH); if (json != null) { imagePatchArray = new JSONArray(json); } } catch (JSONException e) { Timber.e(e); } // cycle over the patches and interpret them if (imagePatchArray != null) { // if this strip is of type 'GROUP', take the first image and use that for all the patches AtomicInteger workCounter; if (brand.getGroupingType() == StripTest.GroupType.GROUP) { workCounter = new AtomicInteger(1); // handle grouping case boolean isInvalidStrip = FileUtil.fileExists(this, Constant.STRIP + "0" + Constant.ERROR); strip = ResultUtil.getMatFromFile(this, patches.get(0).getId()); if (strip != null) { // create empty mat to serve as a template resultImage = new Mat(0, strip.cols(), CvType.CV_8UC3, new Scalar(MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE)); new BitmapTask(isInvalidStrip, strip, true, brand, patches, 0, workCounter).execute(strip); } } else { workCounter = new AtomicInteger(patches.size()); // if this strip is of type 'INDIVIDUAL' handle patch by patch for (int i = 0; i < patches.size(); i++) { // handle patch // read strip from file strip = ResultUtil.getMatFromFile(this, patches.get(i).getId()); if (strip != null) { if (i == 0) { // create empty mat to serve as a template resultImage = new Mat(0, strip.cols(), CvType.CV_8UC3, new Scalar(MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE)); } new BitmapTask(false, strip, false, brand, patches, i, workCounter).execute(strip); } } } } else { TextView textView = new TextView(this); textView.setText(R.string.noData); LinearLayout layout = (LinearLayout) findViewById(R.id.layout_results); layout.addView(textView); } findViewById(R.id.progressBar).setVisibility(View.GONE); findViewById(R.id.testProgress).setVisibility(View.GONE); }
From source file:org.akvo.caddisfly.sensor.colorimetry.strip.util.ResultUtil.java
License:Open Source License
/** * Create Mat with swatches for the colors in the color chart range and also write the value. * * @param colors the colors to draw//from ww w. j a v a 2 s .co m * @param width the final width of the Mat * @return the created Mat */ @NonNull public static Mat createColorRangeMatSingle(@NonNull JSONArray colors, int width) { double gutterWidth = X_MARGIN; if (colors.length() > 10) { gutterWidth = 2d; width -= 10; } double xTranslate = (double) width / (double) colors.length(); Mat colorRangeMat = new Mat((int) xTranslate + MEASURE_LINE_HEIGHT, width, CvType.CV_8UC3, LAB_WHITE); double previousPos = 0; for (int d = 0; d < colors.length(); d++) { try { JSONObject colorObj = colors.getJSONObject(d); double value = colorObj.getDouble(SensorConstants.VALUE); JSONArray lab = colorObj.getJSONArray(SensorConstants.LAB); Scalar scalarLab = new Scalar((lab.getDouble(0) / 100) * MAX_RGB_INT_VALUE, lab.getDouble(1) + 128, lab.getDouble(2) + 128); //draw a rectangle filled with color for result value Point topLeft = new Point(xTranslate * d, Y_COLOR_RECT); Point bottomRight = new Point(topLeft.x + xTranslate - gutterWidth, Y_COLOR_RECT + xTranslate); Imgproc.rectangle(colorRangeMat, topLeft, bottomRight, scalarLab, -1); Size textSizeValue = Imgproc.getTextSize(DECIMAL_FORMAT.format(value), Core.FONT_HERSHEY_SIMPLEX, NORMAL_FONT_SCALE, 2, null); double x = topLeft.x + (bottomRight.x - topLeft.x) / 2 - textSizeValue.width / 2; //draw color value below rectangle. Skip if too close to the previous label if (x > previousPos + MIN_COLOR_LABEL_WIDTH || d == 0) { previousPos = x; String label; //no decimal places if too many labels to fit if (colors.length() > 10) { label = String.format(Locale.getDefault(), "%.0f", value); } else { label = DECIMAL_FORMAT.format(value); } //adjust x if too close to edge if (x + textSizeValue.width > colorRangeMat.width()) { x = colorRangeMat.width() - textSizeValue.width; } Imgproc.putText(colorRangeMat, label, new Point(x, Y_COLOR_RECT + xTranslate + textSizeValue.height + BORDER_SIZE), Core.FONT_HERSHEY_SIMPLEX, NORMAL_FONT_SCALE, LAB_GREY, 2, Core.LINE_AA, false); } } catch (JSONException e) { Timber.e(e); } } return colorRangeMat; }
From source file:org.akvo.caddisfly.sensor.colorimetry.strip.util.ResultUtil.java
License:Open Source License
/** * Create Mat to hold a rectangle for each color with the corresponding value. * * @param patches the patches on the strip * @param width the width of the Mat to be returned * @return the Mat with the color range/*w ww.ja v a 2 s . c om*/ */ @NonNull public static Mat createColorRangeMatGroup(@NonNull List<StripTest.Brand.Patch> patches, int width) { // vertical size of mat: size of color block - X_MARGIN + top distance double xTranslate = (double) width / (double) patches.get(0).getColors().length(); int numPatches = patches.size(); Mat colorRangeMat = new Mat((int) Math.ceil(numPatches * (xTranslate + X_MARGIN) - X_MARGIN), width, CvType.CV_8UC3, LAB_WHITE); JSONArray colors; int offset = 0; for (int p = 0; p < numPatches; p++) { colors = patches.get(p).getColors(); for (int d = 0; d < colors.length(); d++) { try { JSONObject colorObj = colors.getJSONObject(d); double value = colorObj.getDouble(SensorConstants.VALUE); JSONArray lab = colorObj.getJSONArray(SensorConstants.LAB); Scalar scalarLab = new Scalar((lab.getDouble(0) / 100) * MAX_RGB_INT_VALUE, lab.getDouble(1) + 128, lab.getDouble(2) + 128); //draw a rectangle filled with color for result value Point topLeft = new Point(xTranslate * d, offset); Point bottomRight = new Point(topLeft.x + xTranslate - X_MARGIN, xTranslate + offset - X_MARGIN); Imgproc.rectangle(colorRangeMat, topLeft, bottomRight, scalarLab, -1); //draw color value below rectangle if (p == 0) { Size textSizeValue = Imgproc.getTextSize(DECIMAL_FORMAT.format(value), Core.FONT_HERSHEY_SIMPLEX, NORMAL_FONT_SCALE, 1, null); Point centerText = new Point( topLeft.x + (bottomRight.x - topLeft.x) / 2 - textSizeValue.width / 2, colorRangeMat.height() - textSizeValue.height); Imgproc.putText(colorRangeMat, DECIMAL_FORMAT.format(value), centerText, Core.FONT_HERSHEY_SIMPLEX, NORMAL_FONT_SCALE, LAB_GREY, 2, Core.LINE_AA, false); } } catch (JSONException e) { Timber.e(e); } } offset += xTranslate; } return colorRangeMat; }
From source file:org.akvo.caddisfly.sensor.colorimetry.strip.util.ResultUtil.java
License:Open Source License
@NonNull public static Mat concatenate(@NonNull Mat m1, @NonNull Mat m2) { int width = Math.max(m1.cols(), m2.cols()); int height = m1.rows() + m2.rows(); Mat result = new Mat(height, width, CvType.CV_8UC3, new Scalar(MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE)); // rect works with x, y, width, height Rect roi1 = new Rect(0, 0, m1.cols(), m1.rows()); Mat roiMat1 = result.submat(roi1);/* w ww .jav a 2 s. c o m*/ m1.copyTo(roiMat1); Rect roi2 = new Rect(0, m1.rows(), m2.cols(), m2.rows()); Mat roiMat2 = result.submat(roi2); m2.copyTo(roiMat2); return result; }
From source file:org.akvo.caddisfly.sensor.colorimetry.strip.util.ResultUtil.java
License:Open Source License
@NonNull public static Mat concatenateHorizontal(@NonNull Mat m1, @NonNull Mat m2) { int width = m1.cols() + m2.cols() + HORIZONTAL_MARGIN; int height = Math.max(m1.rows(), m2.rows()); Mat result = new Mat(height, width, CvType.CV_8UC3, new Scalar(MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE)); // rect works with x, y, width, height Rect roi1 = new Rect(0, 0, m1.cols(), m1.rows()); Mat roiMat1 = result.submat(roi1);//from w w w . ja v a 2 s . c o m m1.copyTo(roiMat1); Rect roi2 = new Rect(m1.cols() + HORIZONTAL_MARGIN, 0, m2.cols(), m2.rows()); Mat roiMat2 = result.submat(roi2); m2.copyTo(roiMat2); return result; }
From source file:org.ar.rubik.MonoChromatic.java
License:Open Source License
/** * Use mask operation and then min max.//w w w .jav a2 s . c o m * This solution consumes about 20 minutes per frame! * * @param original_image * @return */ @SuppressWarnings("unused") private static Mat monochromaticMedianImageFilterUtilizingOpenCv2(Mat original_image) { final Size imageSize = original_image.size(); final int numColumns = (int) original_image.size().width; final int numRows = (int) original_image.size().height; final int bufferSize = numColumns * numRows; final int span = (int) 7; final int accuracy = (int) 5; Mat hsv_image = new Mat(imageSize, CvType.CV_8UC3); Imgproc.cvtColor(original_image, hsv_image, Imgproc.COLOR_RGB2HLS); List<Mat> channels = new LinkedList<Mat>(); Core.split(hsv_image, channels); Mat hueMat = channels.get(0); Mat lumMat = channels.get(1); Mat satMat = channels.get(2); // Output byte array for speed efficiency Mat monochromatic_image = new Mat(imageSize, CvType.CV_8UC1); byte[] monochromaticByteArray = new byte[bufferSize]; Mat mask = Mat.zeros(numRows, numColumns, CvType.CV_8UC1); Log.i(Constants.TAG, "Begin MonoChromatic CV"); for (int row = 0; row < numRows; row++) { byte result_pixel = 0; for (int col = 0; col < numColumns; col++) { if (col < span || (col >= numColumns - span)) result_pixel = 0; // Just put in black else if (row < span || (row >= numRows - span)) result_pixel = 0; // Just put in black else { // Log.i(Constants.TAG, "Creating Mask at " + row +"," + col); Core.rectangle(mask, new Point(row, col), new Point(row + span, col + span), new Scalar(1, 1, 1)); // Core.MinMaxLocResult minMaxResult = Core.minMaxLoc(hueMat, mask); Mat subset = new Mat(); hueMat.copyTo(subset, mask); Core.MinMaxLocResult minMaxResult = Core.minMaxLoc(subset); if (((minMaxResult.maxVal - minMaxResult.maxVal) < accuracy)) //&& (lum_max - lum_min < accuracy) && (sat_max - sat_min < accuracy) ) result_pixel = (byte) 128; else result_pixel = (byte) 0; // Log.i(Constants.TAG, "Completed Mask at " + row +"," + col); Core.rectangle(mask, new Point(row, col), new Point(row + span, col + span), new Scalar(0, 0, 0)); } if ((col >= span / 2) && (row >= span / 2)) monochromaticByteArray[(row - span / 2) * numColumns + (col - span / 2)] = result_pixel; } Log.i(Constants.TAG, "Completed Row: " + row); } monochromatic_image.put(0, 0, monochromaticByteArray); Log.i(Constants.TAG, "Completed MonoChromatic CV"); // System.exit(0); return monochromatic_image; }
From source file:org.ar.rubik.MonoChromatic.java
License:Open Source License
/** * Use OpenCV minMax./* www . j a v a 2 s . c o m*/ * * However, this is enormously slow, taking 10 minutes per frame! Why? * I think because it is effective O(O^4) in computation. * * @param original_image * @return */ @SuppressWarnings("unused") private static Mat monochromaticMedianImageFilterUtilizingOpenCv(Mat original_image) { final Size imageSize = original_image.size(); final int numColumns = (int) original_image.size().width; final int numRows = (int) original_image.size().height; final int bufferSize = numColumns * numRows; final int span = (int) 7; final int accuracy = (int) 5; Mat hsv_image = new Mat(imageSize, CvType.CV_8UC3); Imgproc.cvtColor(original_image, hsv_image, Imgproc.COLOR_RGB2HLS); List<Mat> channels = new LinkedList<Mat>(); Core.split(hsv_image, channels); Mat hueMat = channels.get(0); Mat lumMat = channels.get(1); Mat satMat = channels.get(2); // Output byte array for speed efficiency Mat monochromatic_image = new Mat(imageSize, CvType.CV_8UC1); byte[] monochromaticByteArray = new byte[bufferSize]; Mat mask = Mat.zeros(numRows, numColumns, CvType.CV_8UC1); Log.i(Constants.TAG, "Begin MonoChromatic CV"); for (int row = 0; row < numRows; row++) { byte result_pixel = 0; for (int col = 0; col < numColumns; col++) { if (col < span || (col >= numColumns - span)) result_pixel = 0; // Just put in black else if (row < span || (row >= numRows - span)) result_pixel = 0; // Just put in black else { // Log.i(Constants.TAG, "Creating Mask at " + row +"," + col); Core.rectangle(mask, new Point(row, col), new Point(row + span, col + span), new Scalar(1, 1, 1)); Core.MinMaxLocResult minMaxResult = Core.minMaxLoc(hueMat, mask); if (((minMaxResult.maxVal - minMaxResult.maxVal) < accuracy)) //&& (lum_max - lum_min < accuracy) && (sat_max - sat_min < accuracy) ) result_pixel = (byte) 128; else result_pixel = (byte) 0; // Log.i(Constants.TAG, "Completed Mask at " + row +"," + col); Core.rectangle(mask, new Point(row, col), new Point(row + span, col + span), new Scalar(0, 0, 0)); } if ((col >= span / 2) && (row >= span / 2)) monochromaticByteArray[(row - span / 2) * numColumns + (col - span / 2)] = result_pixel; } Log.i(Constants.TAG, "Completed Row: " + row); } monochromatic_image.put(0, 0, monochromaticByteArray); Log.i(Constants.TAG, "Completed MonoChromatic CV"); // System.exit(0); return monochromatic_image; }
From source file:org.firstinspires.ftc.teamcode.libraries.VuforiaBallLib.java
protected BallColor getBallColor() { //get frame from vuforia try {//from w w w. j a v a2 s . c om Mat out = getFrame(); //get vuforia's real position matrix Matrix34F goodCodeWritten = ((VuforiaDefaultListenerShim) relicTemplate.getListener()).getRealPose(); if (goodCodeWritten == null) return BallColor.Undefined; this.tempMark = RelicRecoveryVuMark.from(relicTemplate); final float[][] ballPoints = new float[4][2]; //the actual color determination for (int i = 8; i < point.length; i++) ballPoints[i - 8] = Tool.projectPoint(camCal, goodCodeWritten, point[i]).getData(); Point imagePoints[] = new Point[ballPoints.length]; //convert points to opencv language for (int i = 0; i < ballPoints.length; i++) imagePoints[i] = new Point((int) ballPoints[i][0], (int) ballPoints[i][1]); //calculate points from projection //find the midpoint between the two points int leftXPoint = (int) ((imagePoints[0].x + imagePoints[1].x) / 2.0); int leftYPoint = (int) ((imagePoints[0].y + imagePoints[1].y) / 2.0); //find the y distande between the two int leftDist = (int) (Math.abs(imagePoints[0].y - imagePoints[1].y) / 2.0); int[] leftBall = new int[] { leftXPoint - (leftDist / 2), leftYPoint - (leftDist / 2) }; //find the midpoint between the two points int rightXPoint = (int) ((imagePoints[2].x + imagePoints[3].x) / 2.0); int rightYPoint = (int) ((imagePoints[2].y + imagePoints[3].y) / 2.0); //find the y distande between the two int rightDist = (int) (Math.abs(imagePoints[2].y - imagePoints[3].y) / 2.0); int[] rightBall = new int[] { rightXPoint - (rightDist / 2), rightYPoint - (rightDist / 2) }; //operation: subsquare //take a square mat we are 100% sure will have a ball in it //sum it up and find the average color Scalar leftColor = drawSquare(out, leftBall, leftDist); Scalar rightColor = drawSquare(out, rightBall, rightDist); if (displayData) { float[][] squarePoints = new float[8][2]; for (int i = 0; i < 8; i++) squarePoints[i] = Tool.projectPoint(camCal, goodCodeWritten, point[i]).getData(); Point[] squarePointRay = new Point[squarePoints.length]; for (int i = 0; i < squarePoints.length; i++) squarePointRay[i] = new Point((int) squarePoints[i][0], (int) squarePoints[i][1]); Scalar green = new Scalar(0, 255, 0); for (int i = 0; i < 2; i++) for (int o = 0; o < 4; o++) Imgproc.line(out, squarePointRay[o == 0 ? 3 + i * 4 : i * 4 + o - 1], squarePointRay[i * 4 + o], green); //connect the rectangles for (int i = 0; i < 4; i++) Imgproc.line(out, squarePointRay[i], squarePointRay[i + 4], green); for (int i = 0; i < imagePoints.length; i++) Imgproc.drawMarker(out, imagePoints[i], green); //flip it for display Core.flip(out, out, -1); drawFrame(out); } if (leftColor != null && rightColor != null) { if (leftColor.val[0] < leftColor.val[1] && rightColor.val[0] > rightColor.val[1]) return BallColor.LeftBlue; else if (leftColor.val[0] > leftColor.val[1] && rightColor.val[0] < rightColor.val[1]) return BallColor.LeftRed; else return BallColor.Indeterminate; } else return BallColor.Undefined; } catch (Exception e) { Log.e("OPENCV", e.getMessage()); return BallColor.Undefined; } }
From source file:org.firstinspires.ftc.teamcode.libraries.VuforiaBallLib.java
protected static Scalar drawSquare(Mat src, int[] ballPoint, int ballDist) { //find average left and right ball square //find the average color for all the pixels in that square if (ballPoint[0] >= 0 && ballPoint[1] >= 0 && ballPoint[0] + ballDist < src.cols() && ballPoint[1] + ballDist < src.rows()) { double total[] = new double[3]; for (int x = 0; x < ballDist; x++) for (int y = 0; y < ballDist; y++) { double[] pixel = src.get(y + ballPoint[1], x + ballPoint[0]); total[0] += pixel[0];//www . ja va 2 s. c o m total[1] += pixel[1]; total[2] += pixel[2]; } //make average color Scalar color = new Scalar(total[0] / (ballDist * ballDist), total[1] / (ballDist * ballDist), total[2] / (ballDist * ballDist)); Imgproc.rectangle(src, new Point(ballPoint[0], ballPoint[1]), new Point(ballPoint[0] + ballDist, ballPoint[1] + ballDist), color, -1); return color; } else return null; }