Example usage for org.opencv.core Scalar Scalar

List of usage examples for org.opencv.core Scalar Scalar

Introduction

In this page you can find the example usage for org.opencv.core Scalar Scalar.

Prototype

public Scalar(double v0, double v1, double v2) 

Source Link

Usage

From source file:classes.TextRecognitionPreparer.java

private static Scalar getFillingColor(Scalar userColor, Mat cutout, Mat labels, Mat centers) {

    double minDistance = 1000000;
    Scalar fillingColor = null;//w  w  w.  jav  a2 s .  c  om

    centers.convertTo(centers, CvType.CV_8UC1, 255.0);
    centers.reshape(3);

    List<Mat> clusters = new ArrayList<Mat>();
    for (int i = 0; i < centers.rows(); i++) {
        clusters.add(Mat.zeros(cutout.size(), cutout.type()));
    }

    Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
    for (int i = 0; i < centers.rows(); i++) {
        counts.put(i, 0);
    }

    int rows = 0;
    for (int y = 0; y < cutout.rows(); y++) {
        for (int x = 0; x < cutout.cols(); x++) {
            int label = (int) labels.get(rows, 0)[0];
            int r = (int) centers.get(label, 2)[0];
            int g = (int) centers.get(label, 1)[0];
            int b = (int) centers.get(label, 0)[0];
            counts.put(label, counts.get(label) + 1);
            clusters.get(label).put(y, x, b, g, r);
            rows++;
        }
    }

    Set<Integer> keySet = counts.keySet();
    Iterator<Integer> iterator = keySet.iterator();
    while (iterator.hasNext()) {

        int label = (int) iterator.next();
        int r = (int) centers.get(label, 2)[0];
        int g = (int) centers.get(label, 1)[0];
        int b = (int) centers.get(label, 0)[0];

        Scalar currentColor = new Scalar(r, g, b);

        double distance = getColorDistance(currentColor, userColor);

        if (distance < minDistance) {
            minDistance = distance;
            fillingColor = currentColor;
        }

    }

    return fillingColor;
}

From source file:cn.xiongyihui.webcam.JpegFactory.java

License:Open Source License

public void onPreviewFrame(byte[] data, Camera camera) {
    YuvImage yuvImage = new YuvImage(data, ImageFormat.NV21, mWidth, mHeight, null);

    mJpegOutputStream.reset();/*from ww w  .  j  a  va  2 s.  c o m*/

    try {
        //Log.e(TAG, "Beginning to read values!");
        double distanceTemplateFeatures = this.globalClass.getDistanceTemplateFeatures();
        double xTemplateCentroid = this.globalClass.getXtemplateCentroid();
        double yTemplateCentroid = this.globalClass.getYtemplateCentroid();
        int x0template = this.globalClass.getX0display();
        int y0template = this.globalClass.getY0display();
        int x1template = this.globalClass.getX1display();
        int y1template = this.globalClass.getY1display();
        Mat templateDescriptor = this.globalClass.getTemplateDescriptor();
        MatOfKeyPoint templateKeyPoints = this.globalClass.getKeyPoints();
        KeyPoint[] templateKeyPointsArray = templateKeyPoints.toArray();
        int numberOfTemplateFeatures = this.globalClass.getNumberOfTemplateFeatures();
        int numberOfPositiveTemplateFeatures = this.globalClass.getNumberOfPositiveTemplateFeatures();
        KeyPoint[] normalisedTemplateKeyPoints = this.globalClass.getNormalisedTemplateKeyPoints();
        double normalisedXcentroid = this.globalClass.getNormalisedXcentroid();
        double normalisedYcentroid = this.globalClass.getNormalisedYcentroid();
        int templateCapturedBitmapWidth = this.globalClass.getTemplateCapturedBitmapWidth();
        int templateCapturedBitmapHeight = this.globalClass.getTemplateCapturedBitmapHeight();
        //Log.e(TAG, "Ended reading values!");
        globalClass.setJpegFactoryDimensions(mWidth, mHeight);
        double scalingRatio, scalingRatioHeight, scalingRatioWidth;

        scalingRatioHeight = (double) mHeight / (double) templateCapturedBitmapHeight;
        scalingRatioWidth = (double) mWidth / (double) templateCapturedBitmapWidth;
        scalingRatio = (scalingRatioHeight + scalingRatioWidth) / 2; //Just to account for any minor variations.
        //Log.e(TAG, "Scaling ratio:" + String.valueOf(scalingRatio));
        //Log.e("Test", "Captured Bitmap's dimensions: (" + templateCapturedBitmapHeight + "," + templateCapturedBitmapWidth + ")");

        //Scale the actual features of the image
        int flag = this.globalClass.getFlag();
        if (flag == 0) {
            int iterate = 0;
            int iterationMax = numberOfTemplateFeatures;

            for (iterate = 0; iterate < (iterationMax); iterate++) {
                Log.e(TAG, "Point detected " + iterate + ":(" + templateKeyPointsArray[iterate].pt.x + ","
                        + templateKeyPointsArray[iterate].pt.y + ")");

                if (flag == 0) {
                    templateKeyPointsArray[iterate].pt.x = scalingRatio
                            * (templateKeyPointsArray[iterate].pt.x + (double) x0template);
                    templateKeyPointsArray[iterate].pt.y = scalingRatio
                            * (templateKeyPointsArray[iterate].pt.y + (double) y0template);
                }
                Log.e(TAG, "Scaled points:(" + templateKeyPointsArray[iterate].pt.x + ","
                        + templateKeyPointsArray[iterate].pt.y + ")");
            }

            this.globalClass.setFlag(1);
        }

        templateKeyPoints.fromArray(templateKeyPointsArray);
        //Log.e(TAG, "Template-features have been scaled successfully!");

        long timeBegin = (int) System.currentTimeMillis();
        Mat mYuv = new Mat(mHeight + mHeight / 2, mWidth, CvType.CV_8UC1);
        mYuv.put(0, 0, data);
        Mat mRgb = new Mat();
        Imgproc.cvtColor(mYuv, mRgb, Imgproc.COLOR_YUV420sp2RGB);

        Mat result = new Mat();
        Imgproc.cvtColor(mRgb, result, Imgproc.COLOR_RGB2GRAY);
        int detectorType = FeatureDetector.ORB;
        FeatureDetector featureDetector = FeatureDetector.create(detectorType);
        MatOfKeyPoint keypointsImage = new MatOfKeyPoint();
        featureDetector.detect(result, keypointsImage);
        KeyPoint[] imageKeypoints = keypointsImage.toArray();

        Scalar color = new Scalar(0, 0, 0);

        DescriptorExtractor descriptorExtractor = DescriptorExtractor.create(DescriptorExtractor.ORB);

        Mat imageDescriptor = new Mat();
        descriptorExtractor.compute(result, keypointsImage, imageDescriptor);

        //BRUTEFORCE_HAMMING apparently finds even the suspicious feature-points! So, inliers and outliers can turn out to be a problem

        DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);
        MatOfDMatch matches = new MatOfDMatch();
        matcher.match(imageDescriptor, templateDescriptor, matches);

        //Log.e("Prasad", String.valueOf(mWidth) + "," + String.valueOf(mHeight));

        DMatch[] matchesArray = matches.toArray();

        double minimumMatchDistance = globalClass.getHammingDistance();

        int iDescriptorMax = matchesArray.length;
        int iterateDescriptor;

        double xMatchedPoint, yMatchedPoint;
        int flagDraw = Features2d.NOT_DRAW_SINGLE_POINTS;

        Point point;

        double rHigh = this.globalClass.getRhigh();
        double rLow = this.globalClass.getRlow();
        double gHigh = this.globalClass.getGhigh();
        double gLow = this.globalClass.getGlow();
        double bHigh = this.globalClass.getBhigh();
        double bLow = this.globalClass.getBlow();

        double[] colorValue;
        double red, green, blue;
        int[] featureCount;
        double xKernelSize = 9, yKernelSize = 9;
        globalClass.setKernelSize(xKernelSize, yKernelSize);
        double xImageKernelScaling, yImageKernelScaling;

        xImageKernelScaling = xKernelSize / mWidth;
        yImageKernelScaling = yKernelSize / mHeight;
        int[][] kernel = new int[(int) xKernelSize][(int) yKernelSize];
        double[][] kernelCounter = new double[(int) xKernelSize][(int) yKernelSize];
        int numberKernelMax = 10;
        globalClass.setNumberKernelMax(numberKernelMax);
        int[][][] kernelArray = new int[(int) xKernelSize][(int) yKernelSize][numberKernelMax];
        double featureImageResponse;
        double xImageCentroid, yImageCentroid;
        double xSum = 0, ySum = 0;
        double totalImageResponse = 0;

        for (iterateDescriptor = 0; iterateDescriptor < iDescriptorMax; iterateDescriptor++) {
            if (matchesArray[iterateDescriptor].distance < minimumMatchDistance) {
                //MatchedPoint: Awesome match without color feedback
                xMatchedPoint = imageKeypoints[matchesArray[iterateDescriptor].queryIdx].pt.x;
                yMatchedPoint = imageKeypoints[matchesArray[iterateDescriptor].queryIdx].pt.y;

                colorValue = mRgb.get((int) yMatchedPoint, (int) xMatchedPoint);

                red = colorValue[0];
                green = colorValue[1];
                blue = colorValue[2];

                int xKernelFeature, yKernelFeature;
                //Color feedback
                if ((rLow < red) & (red < rHigh) & (gLow < green) & (green < gHigh) & (bLow < blue)
                        & (blue < bHigh)) {
                    try {
                        featureImageResponse = imageKeypoints[matchesArray[iterateDescriptor].queryIdx].response;
                        if (featureImageResponse > 0) {
                            xSum = xSum + featureImageResponse * xMatchedPoint;
                            ySum = ySum + featureImageResponse * yMatchedPoint;
                            totalImageResponse = totalImageResponse + featureImageResponse;
                            point = imageKeypoints[matchesArray[iterateDescriptor].queryIdx].pt;

                            xKernelFeature = (int) (xMatchedPoint * xImageKernelScaling);
                            yKernelFeature = (int) (yMatchedPoint * yImageKernelScaling);
                            kernelCounter[xKernelFeature][yKernelFeature]++;
                            //Core.circle(result, point, 3, color);
                        }
                    } catch (Exception e) {
                    }
                }
                //Log.e(TAG, iterateDescriptor + ": (" + xMatchedPoint + "," + yMatchedPoint + ")");
            }
        }

        int iKernel = 0, jKernel = 0;
        for (iKernel = 0; iKernel < xKernelSize; iKernel++) {
            for (jKernel = 0; jKernel < yKernelSize; jKernel++) {
                if (kernelCounter[iKernel][jKernel] > 0) {
                    kernel[iKernel][jKernel] = 1;
                } else {
                    kernel[iKernel][jKernel] = 0;
                }
            }
        }

        xImageCentroid = xSum / totalImageResponse;
        yImageCentroid = ySum / totalImageResponse;

        if ((Double.isNaN(xImageCentroid)) | (Double.isNaN(yImageCentroid))) {
            //Log.e(TAG, "Centroid is not getting detected! Increasing hamming distance (error-tolerance)!");
            globalClass.setHammingDistance((int) (minimumMatchDistance + 2));
        } else {
            //Log.e(TAG, "Centroid is getting detected! Decreasing and optimising hamming (error-tolerance)!");
            globalClass.setHammingDistance((int) (minimumMatchDistance - 1));
            int jpegCount = globalClass.getJpegFactoryCallCount();
            jpegCount++;
            globalClass.setJpegFactoryCallCount(jpegCount);
            int initialisationFlag = globalClass.getInitialisationFlag();
            int numberOfDistances = 10;
            globalClass.setNumberOfDistances(numberOfDistances);

            if ((jpegCount > globalClass.getNumberKernelMax()) & (jpegCount > numberOfDistances)) {
                globalClass.setInitialisationFlag(1);
            }

            int[][] kernelSum = new int[(int) xKernelSize][(int) yKernelSize],
                    mask = new int[(int) xKernelSize][(int) yKernelSize];
            int iJpeg, jJpeg;
            kernelSum = globalClass.computeKernelSum(kernel);

            Log.e(TAG, Arrays.deepToString(kernelSum));

            for (iJpeg = 0; iJpeg < xKernelSize; iJpeg++) {
                for (jJpeg = 0; jJpeg < yKernelSize; jJpeg++) {
                    if (kernelSum[iJpeg][jJpeg] > (numberKernelMax / 4)) {//Meant for normalised kernel
                        mask[iJpeg][jJpeg]++;
                    }
                }
            }

            Log.e(TAG, Arrays.deepToString(mask));

            int maskedFeatureCount = 1, xMaskFeatureSum = 0, yMaskFeatureSum = 0;

            for (iJpeg = 0; iJpeg < xKernelSize; iJpeg++) {
                for (jJpeg = 0; jJpeg < yKernelSize; jJpeg++) {
                    if (mask[iJpeg][jJpeg] == 1) {
                        xMaskFeatureSum = xMaskFeatureSum + iJpeg;
                        yMaskFeatureSum = yMaskFeatureSum + jJpeg;
                        maskedFeatureCount++;
                    }
                }
            }

            double xMaskMean = xMaskFeatureSum / maskedFeatureCount;
            double yMaskMean = yMaskFeatureSum / maskedFeatureCount;

            double xSquaredSum = 0, ySquaredSum = 0;
            for (iJpeg = 0; iJpeg < xKernelSize; iJpeg++) {
                for (jJpeg = 0; jJpeg < yKernelSize; jJpeg++) {
                    if (mask[iJpeg][jJpeg] == 1) {
                        xSquaredSum = xSquaredSum + (iJpeg - xMaskMean) * (iJpeg - xMaskMean);
                        ySquaredSum = ySquaredSum + (jJpeg - yMaskMean) * (jJpeg - yMaskMean);
                    }
                }
            }

            double xRMSscaled = Math.sqrt(xSquaredSum);
            double yRMSscaled = Math.sqrt(ySquaredSum);
            double RMSimage = ((xRMSscaled / xImageKernelScaling) + (yRMSscaled / yImageKernelScaling)) / 2;
            Log.e(TAG, "RMS radius of the image: " + RMSimage);

            /*//Command the quadcopter and send PWM values to Arduino
            double throttlePWM = 1500, yawPWM = 1500, pitchPWM = 1500;
            double deltaThrottle = 1, deltaYaw = 1, deltaPitch = 1;
                    
            throttlePWM = globalClass.getThrottlePWM();
            pitchPWM = globalClass.getPitchPWM();
            yawPWM = globalClass.getYawPWM();
                    
            deltaThrottle = globalClass.getThrottleDelta();
            deltaPitch = globalClass.getPitchDelta();
            deltaYaw = globalClass.getYawDelta();
                    
            if(yImageCentroid>yTemplateCentroid) {
            throttlePWM = throttlePWM + deltaThrottle;
            }else{
            throttlePWM = throttlePWM - deltaThrottle;
            }
                    
            if(RMSimage>distanceTemplateFeatures) {
            pitchPWM = pitchPWM + deltaPitch;
            }else{
            pitchPWM = pitchPWM - deltaPitch;
            }
                    
            if(xImageCentroid>xTemplateCentroid) {
            yawPWM = yawPWM + deltaYaw;
            }else{
            yawPWM = yawPWM - deltaYaw;
            }
                    
            if(1000>throttlePWM){   throttlePWM = 1000; }
                    
            if(2000<throttlePWM){   throttlePWM = 2000; }
                    
            if(1000>pitchPWM){  pitchPWM = 1000;    }
                    
            if(2000<pitchPWM){  pitchPWM = 2000;    }
                    
            if(1000>yawPWM){    yawPWM = 1000;  }
                    
            if(2000<yawPWM){    yawPWM = 2000;  }
                    
            globalClass.setPitchPWM(pitchPWM);
            globalClass.setYawPWM(yawPWM);
            globalClass.setThrottlePWM(throttlePWM);*/

            //Display bounding circle
            int originalWidthBox = x1template - x0template;
            int originalHeightBox = y1template - y0template;

            double scaledBoundingWidth = (originalWidthBox * RMSimage / distanceTemplateFeatures);
            double scaledBoundingHeight = (originalHeightBox * RMSimage / distanceTemplateFeatures);

            double displayRadius = (scaledBoundingWidth + scaledBoundingHeight) / 2;
            displayRadius = displayRadius * 1.4826;
            displayRadius = displayRadius / numberKernelMax;
            double distanceAverage = 0;
            if (Double.isNaN(displayRadius)) {
                //Log.e(TAG, "displayRadius is NaN!");
            } else {
                distanceAverage = globalClass.imageDistanceAverage(displayRadius);
                //Log.e(TAG, "Average distance: " + distanceAverage);
            }

            if ((Double.isNaN(xImageCentroid)) | Double.isNaN(yImageCentroid)) {
                //Log.e(TAG, "Centroid is NaN!");
            } else {
                globalClass.centroidAverage(xImageCentroid, yImageCentroid);
            }

            if (initialisationFlag == 1) {
                //int displayRadius = 50;

                Point pointDisplay = new Point();
                //pointDisplay.x = xImageCentroid;
                //pointDisplay.y = yImageCentroid;
                pointDisplay.x = globalClass.getXcentroidAverageGlobal();
                pointDisplay.y = globalClass.getYcentroidAverageGlobal();
                globalClass.centroidAverage(xImageCentroid, yImageCentroid);
                int distanceAverageInt = (int) distanceAverage;
                Core.circle(result, pointDisplay, distanceAverageInt, color);
            }

        }

        Log.e(TAG, "Centroid in the streamed image: (" + xImageCentroid + "," + yImageCentroid + ")");
        /*try {
        //Features2d.drawKeypoints(result, keypointsImage, result, color, flagDraw);
        Features2d.drawKeypoints(result, templateKeyPoints, result, color, flagDraw);
        }catch(Exception e){}*/

        //Log.e(TAG, "High (R,G,B): (" + rHigh + "," + gHigh + "," + bHigh + ")");
        //Log.e(TAG, "Low (R,G,B): (" + rLow + "," + gLow + "," + bLow + ")");

        //Log.e(TAG, Arrays.toString(matchesArray));

        try {
            Bitmap bmp = Bitmap.createBitmap(result.cols(), result.rows(), Bitmap.Config.ARGB_8888);
            Utils.matToBitmap(result, bmp);
            //Utils.matToBitmap(mRgb, bmp);
            bmp.compress(Bitmap.CompressFormat.JPEG, mQuality, mJpegOutputStream);
        } catch (Exception e) {
            Log.e(TAG, "JPEG not working!");
        }

        long timeEnd = (int) System.currentTimeMillis();
        Log.e(TAG, "Time consumed is " + String.valueOf(timeEnd - timeBegin) + "milli-seconds!");

        mJpegData = mJpegOutputStream.toByteArray();

        synchronized (mJpegOutputStream) {
            mJpegOutputStream.notifyAll();
        }
    } catch (Exception e) {
        Log.e(TAG, "JPEG-factory is not working!");
    }

}

From source file:com.astrocytes.core.operationsengine.OperationsImpl.java

License:Open Source License

@Deprecated
private Mat drawAstrocyteCenters() {
    if (astrocytesCenters == null) {
        return sourceImage;
    }/* www  .ja  v a2  s  .  c  o  m*/

    Mat result = sourceImage.clone();
    Scalar color = new Scalar(108, 240, 3);

    for (Point center : astrocytesCenters) {
        Imgproc.circle(result, center, 3, color);
    }

    return result;
}

From source file:com.astrocytes.core.operationsengine.OperationsImpl.java

License:Open Source License

@Deprecated
private Mat drawNeuronsCenters(Mat src) {
    if (src == null) {
        src = sourceImage.clone();/*  ww w  .ja  v  a2 s .c o m*/
    }
    if (neurons == null) {
        return src;
    }

    Mat result = src.clone();
    Scalar color = new Scalar(250, 10, 19);

    for (Neuron neuron : neurons) {
        Imgproc.circle(result, neuron.getCenter(), 4, color, 2);
    }

    return result;
}

From source file:com.astrocytes.core.operationsengine.OperationsImpl.java

License:Open Source License

@Deprecated
private Mat drawLayerBounds() {
    if (layerBounds == null) {
        return sourceImage;
    }/*from   w  w  w . j  a  v a 2s. c om*/

    Mat result = sourceImage.clone();

    for (int i = 0; i < layerBounds.rows(); i++) {
        Scalar color = new Scalar(250, 20, 18);
        if (i == 0 || i == layerBounds.rows() - 1) {
            color = new Scalar(18, 20, 250);
        }

        for (int j = 0; j < layerBounds.cols(); j++) {
            Imgproc.circle(result, new Point(j, layerBounds.get(i, j)[0]), 1, color, -1);
        }
    }

    return result;
}

From source file:com.carver.paul.truesight.ImageRecognition.ImageTools.java

License:Open Source License

public static void drawLinesOnImage(Mat lines, Mat image) {
    for (int i = 0; i < lines.rows(); i++) {
        double[] val = lines.get(i, 0);
        Imgproc.line(image, new Point(val[0], val[1]), new Point(val[2], val[3]), new Scalar(0, 255, 0), 2);
    }/*from  w ww . j  a va 2  s  .c o m*/
}

From source file:com.carver.paul.truesight.ImageRecognition.RecognitionModel.java

License:Open Source License

public static List<Mat> findHeroTopLinesInImage(Mat photo, List<List<Integer>> colourRanges, int lowerHsvS,
        int lowerHsvV, int upperHsvS, int upperHsvV) {
    List<Mat> linesList = new ArrayList<>();
    int pos = 0;//  www.  j a v  a 2  s .co m
    int photoWidth = photo.width();

    for (List<Integer> colourRange : colourRanges) {
        int minX;
        int maxX;

        if (colourRanges.size() == 1) {
            minX = 0;
            maxX = photoWidth;
        } else {
            minX = pos * photoWidth / 6;
            maxX = (2 + pos) * photoWidth / 6;
        }

        Scalar lowerHsv = new Scalar(colourRange.get(0), lowerHsvS, lowerHsvV);
        Scalar upperHsv = new Scalar(colourRange.get(1), upperHsvS, upperHsvV);

        Mat subMat = photo.submat(0, photo.height() / 2, minX, maxX);
        Mat mask = new Mat();
        ImageTools.MaskAColourFromImage(subMat, lowerHsv, upperHsv, mask);

        Mat lines = new Mat();

        // note, this is the part that takes most time.
        ImageTools.getLineFromTopRectMask(mask, lines, photoWidth / 7); //USED TO BE 8!!!!

        adjustXPosOfLines(lines, minX);
        linesList.add(lines);

        //   Main.DrawMatInImageBox(mask, maskImage); // just for debug
        pos++;
    }

    return linesList;
}

From source file:com.carver.paul.truesight.ImageRecognition.RecognitionModel.java

License:Open Source License

/**
 * Draws the line onto the image, used for debugging.
 * @param img/*from  ww  w . j  a v a2  s . c o  m*/
 */
public void Draw(Mat img) {
    Imgproc.rectangle(img, new org.opencv.core.Point(rect.left, rect.top),
            new org.opencv.core.Point(rect.right, rect.bottom), new Scalar(0, 255, 0), 2);
}

From source file:com.example.colordetector.CamMainActivity.java

License:Apache License

public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    // The frame currently captured by the camera, converted in the color RGBA
    rgbaFrame = inputFrame.rgba();//from   w w  w .j  av  a2  s.  com

    // Convert the frame in the HSV color space, to be able to identify the color with the thresholds
    Imgproc.cvtColor(rgbaFrame, rgbFrame, Imgproc.COLOR_RGBA2RGB); // Cant't convert directly rgba->hsv
    Imgproc.cvtColor(rgbFrame, hsvFrame, Imgproc.COLOR_RGB2HSV);

    // Create a mask with ONLY zones of the chosen color on the frame currently captured
    Core.inRange(hsvFrame, thresMin, thresMax, inRangeMask);
    filteredFrame.setTo(new Scalar(0, 0, 0));
    rgbFrame.copyTo(filteredFrame, inRangeMask);

    // if the method of shooting image is set to manual, exit and return the filtered image...
    if (!methodAuto) {
        return filteredFrame;
    }

    //...else it was setted the automatic method, so continue with the method
    // Check the H channel of the image to see if the searched color is present on the frame
    Core.extractChannel(filteredFrame, hChannel, 0);

    /* There are two method to verify the color presence; below a little explanation */

    /* checkRange: if almost one pixel of the searched color is found, continue with the countdown
     * Pro -> fast.
     * Versus -> less accurate, possible presence of false positive depending the quality of the camera
     * if(!Core.checkRange(hChannel, true, 0, 1)){ */

    /* Percentage: count the pixel of the searched color, and if there are almost the
     * 0.1% of total pixel of the frame with the searched color, continue with the countdown
     * Pro: more accurate, lower risk of false positive
     * Versus: slower than checkRange
     * N.B.: the threshold percentage is imposted with a low value, otherwise small object will not be seen */

    int perc = Core.countNonZero(hChannel); // Percentage
    if (perc > (frameDim * 0.001)) {
        // if the shooting method is setted to 'immediate', the photo is returned now;
        // otherwise continue with the countdown
        if (!countDown) {
            takePicture();
            return rgbaFrame;
        }

        // 'point' is where the countdown will be visualized; in that case at
        //  a quarter of height and width than left up angle
        Point point = new Point(rgbaFrame.cols() >> 2, rgbaFrame.rows() >> 2);

        // Update the osd countdown every 75*8 ms (if color searched is present)
        // Use the division in 75 ms cause a higher value would give the user the feeling of screen/app 'blocked'.
        if (timeToElapse % 8 == 0) {
            if (osdSecond.compareTo("") == 0)
                osdSecond = ((Integer) (timeToElapse >> 3)).toString();
            else
                osdSecond = osdSecond.concat(".." + (((Integer) (timeToElapse >> 3)).toString()));
            Core.putText(rgbaFrame, osdSecond, point, 1, 3, Scalar.all(255));
        }
        timeToElapse -= 1;

        // the user has framed an object for more than 3 seconds; shoot the photo
        if (timeToElapse <= 0) {
            timeToElapse = 24;
            takePicture();
        }
        // the user has framed an object for less than 3 seconds; wait
        else {
            try {
                synchronized (this) {
                    wait(75);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    // the user has NOT framed a color searched object; reset osd
    else {
        timeToElapse = 24;
        osdSecond = "";
    }
    return rgbaFrame;
}

From source file:com.example.sarthuak.opencv.MainActivity.java

public Mat onCameraFrame(CvCameraViewFrame inputFrame) {

    // TODO Auto-generated method stub
    final int viewMode = mViewMode;
    switch (viewMode) {

    case VIEW_MODE_RGBA:
        // input frame has RBGA format
        mRgba = inputFrame.rgba();//from  ww w.  j ava  2s  .  c o m
        break;
    case VIEW_MODE_CANNY:
        // input frame has gray scale format
        mRgba = inputFrame.rgba();
        Imgproc.Canny(inputFrame.gray(), mRgbaF, 80, 100);
        Imgproc.cvtColor(mRgbaF, mRgba, Imgproc.COLOR_GRAY2RGBA, 4);
        break;

    case VIEW_MODE_ocr:
        startActivity(new Intent(this, ScanLicensePlateActivity.class));
        break;

    case VIEW_MODE_new:
        Mat mRgba;

        mRgba = inputFrame.rgba();
        drawing = mRgba.clone();

        mRgbaT = drawing;

        Imgproc.cvtColor(drawing, mRgbaT, Imgproc.COLOR_BGR2GRAY);

        org.opencv.core.Size s = new Size(1, 1);
        Imgproc.GaussianBlur(mRgbaT, mRgbaT, s, 0, 0);

        Imgproc.Canny(mRgbaT, mRgbaT, 100, 255);
        Mat element = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(5, 5));
        Imgproc.dilate(mRgbaT, mRgbaT, element);
        List<MatOfPoint> contours = new ArrayList<>();

        Imgproc.findContours(drawing, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE,
                new Point(0, 0));
        double maxArea = -1;
        int maxAreaIdx = -1;

        for (int idx = 0; idx < contours.size(); idx++) {
            Mat contour = contours.get(idx);

            double contourarea = Imgproc.contourArea(contour);
            if (contourarea > maxArea) {

                maxArea = contourarea;
                maxAreaIdx = idx;
            }
        }

        Imgproc.drawContours(mRgba, contours, maxAreaIdx, new Scalar(255, 0, 0), 5);

    }
    return mRgba; // This function must return

}