Example usage for org.opencv.imgproc Imgproc GaussianBlur

List of usage examples for org.opencv.imgproc Imgproc GaussianBlur

Introduction

In this page you can find the example usage for org.opencv.imgproc Imgproc GaussianBlur.

Prototype

public static void GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX, double sigmaY) 

Source Link

Usage

From source file:Questao2.java

void gaussiano() {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    String url = escolherUrl();// www. j av  a 2 s .  c om

    /**
     * Transforma imagem em matriz para facilitar manipulacao
     */
    Mat img = Imgcodecs.imread(url);
    /**
     * Cria matriz de destino
     */
    Mat dst = new Mat();
    /**
     * Aplica o filtro gaussiano
     * GaussianBlur(imagem original, imgagem destino, tamanho da mascara, sygmaX, sygmaY)
     */
    System.out.println("Dimenses da mscara: ");
    System.out.print("X: ");
    int mx = in.nextInt();
    System.out.print("Y: ");
    int my = in.nextInt();

    System.out.println("Valores Sygma: ");
    System.out.print("X: ");
    int sx = in.nextInt();
    System.out.print("Y: ");
    int sy = in.nextInt();
    Imgproc.GaussianBlur(img, dst, new Size(mx, my), sx, sy);
    /**
     * Salva resultado em gaussian-blur.jpg
     */
    Imgcodecs.imwrite("gaussian-blur.jpg", dst);
    showResult("gaussian-blur.jpg");
}

From source file:KoImgProc.java

License:Open Source License

/**
 * Takes a Mat and performs a series of image analysis and filtering steps
 * to detect stones in the image and filter out false circles.
 * @param color //  w w  w  .j  av  a  2 s  . c  om
 *             The input Mat to perform analysis on. Must be a 3-channel,
 *             8-bit BGR color image. 
 * @return An array of KoCircle objects that represent stones that were
 *          detected on the board.
 */
public static ArrayList<KoCircle> detectStones(Mat color) {
    // Create 2 Mats we'll need for image processing
    Mat grey = new Mat();
    Mat blurred = new Mat();
    Imgproc.cvtColor(color, grey, Imgproc.COLOR_BGR2GRAY); // Convert to greyscale
    Imgproc.GaussianBlur(grey, grey, new Size(9, 9), 2, 2);
    Imgproc.GaussianBlur(color, blurred, new Size(9, 9), 2, 2);

    int widthInPixels = color.cols();
    //int heightInPixels = color.cols();

    // widthInPixels will be replaced by dimensions from a camera overlay that aligns with the board
    ArrayList<KoCircle> stones = detectStones(grey, widthInPixels / 50, widthInPixels / 30, widthInPixels / 30,
            CANNY_DETECTOR_THRESHOLD_HIGH);
    double aveRadius = getAverageRadius(stones);

    // Calculate more accurate inputs to HoughCircles given the average radius
    int minCircleRadius = (int) (0.9 * aveRadius);
    int maxCircleRadius = (int) (1.1 * aveRadius);
    int minDist = (int) (aveRadius * 1.75);

    stones = detectStones(grey, minCircleRadius, maxCircleRadius, minDist, CANNY_DETECTOR_THRESHOLD_MED);
    TreeMap<String, Double[]> colorData = getColorData(stones, blurred, grey);

    if (VERBOSE) {
        for (String key : colorData.keySet()) {
            Double[] current = colorData.get(key);
            System.out.println("Data for " + key + ":");
            for (int i = 0; i < current.length; i++) {
                System.out.println(current[i]);
            }
        }
    }

    stones = detectStones(grey, minCircleRadius, maxCircleRadius, minDist, CANNY_DETECTOR_THRESHOLD_LOW);

    return filterStones(stones, colorData, aveRadius, grey, blurred);
}

From source file:abc.RomanCharacterPicture.java

public int evaluatePicture() {
    try {//  ww  w .  ja  v  a2 s  . co m
        ITesseract instance = new Tesseract();

        MatToBufImg webcamImageBuff = new MatToBufImg();

        webcamImageBuff.setMatrix(webcam_image, ".jpg");
        double heightRatio = (double) webcamImageBuff.getBufferedImage().getHeight()
                / (double) webcam_image.height();
        double widthRatio = (double) webcamImageBuff.getBufferedImage().getWidth()
                / (double) webcam_image.width();
        int x1 = this.leftRectangle.getxPos();
        int y1 = this.leftRectangle.getyPos();
        int x2 = this.rightRectangle.getxPos();
        int y2 = this.rightRectangle.getyPos();
        Rect rect = new Rect(leftRectangle.getxPos(), leftRectangle.getyPos(),
                (rightRectangle.getxPos() - leftRectangle.getxPos()),
                (rightRectangle.getyPos() - leftRectangle.getyPos()));
        //Rect rect = new Rect(new Point(leftRectangle.getxPos(), leftRectangle.getyPos()), new Point(leftRectangle.getxPos(), rightRectangle.getyPos()), , (rightRectangle.getxPos()-leftRectangle.getxPos()));
        Mat subImageMat = webcam_image.submat(rect);

        BufferedImage romanCharacter = webcamImageBuff.getBufferedImage().getSubimage((int) (x1 * widthRatio),
                (int) (y1 * heightRatio), (int) (widthRatio * (x2 - x1)), (int) (heightRatio * (y2 - y1)));

        //int[] pixels = ((DataBufferInt) romanCharacter.getRaster().getDataBuffer()).getData();
        //Mat subImageMat = new Mat(romanCharacter.getHeight(), romanCharacter.getWidth(), CvType.CV_8UC3);
        //subImageMat.put(0, 0, pixels);

        Mat hsv_image = new Mat();
        Imgproc.cvtColor(subImageMat, hsv_image, Imgproc.COLOR_BGR2HSV);

        Mat lower_black_hue_range = new Mat();
        Mat upper_black_hue_range = new Mat();

        Core.inRange(hsv_image, new Scalar(0, 0, 0), new Scalar(180, 255, 30), lower_black_hue_range);
        Core.inRange(hsv_image, new Scalar(0, 0, 20), new Scalar(180, 255, 40), upper_black_hue_range);

        Mat black_hue_image = new Mat();
        Core.addWeighted(lower_black_hue_range, 1.0, upper_black_hue_range, 1.0, 0.0, black_hue_image);

        Imgproc.GaussianBlur(black_hue_image, black_hue_image, new Size(9, 9), 2, 2);

        MatToBufImg blackImageBuff = new MatToBufImg();

        blackImageBuff.setMatrix(black_hue_image, ".jpg");
        BufferedImage test = blackImageBuff.getBufferedImage();

        //ImageIO.write(test, "PNG", new FileOutputStream((Math.round(Math.random()*1000))+"dst.png"));
        String result = instance.doOCR(test);
        int counterI = 0;
        for (int i = 0; i < result.length(); i++) {
            if (result.charAt(i) == 'I' || result.charAt(i) == 'l' || result.charAt(i) == '1'
                    || result.charAt(i) == 'i' || result.charAt(i) == 'L' || result.charAt(i) == 'j'
                    || result.charAt(i) == 'J') {
                counterI++;
            }
        }

        int counterV = 0;
        for (int i = 0; i < result.length(); i++) {
            if (result.charAt(i) == 'V' || result.charAt(i) == 'v' || result.charAt(i) == 'W'
                    || result.charAt(i) == 'w' || result.contains("\\//")) {
                counterV++;
            }
        }
        //System.out.println("Result: "+result+ " calc:" + (counterI + (counterV * 5)));
        return (counterI + (counterV * 5));
    } catch (Exception ex) {
        //System.out.println(ex.getMessage());
        ex.printStackTrace();
        return 0;
    }

}

From source file:ac.robinson.ticqr.TickBoxImageParserTask.java

License:Apache License

@Override
protected ArrayList<PointF> doInBackground(Void... unused) {
    Log.d(TAG, "Searching for tick boxes of " + mBoxSize + " size");

    // we look for *un-ticked* boxes, rather than ticked, as they are uniform in appearance (and hence easier to
    // detect) - they show up as a box within a box
    ArrayList<PointF> centrePoints = new ArrayList<>();
    int minimumOuterBoxArea = (int) Math.round(Math.pow(mBoxSize, 2));
    int maximumOuterBoxArea = (int) Math.round(Math.pow(mBoxSize * 1.35f, 2));
    int minimumInnerBoxArea = (int) Math.round(Math.pow(mBoxSize * 0.5f, 2));

    // image adjustment - blurSize, blurSTDev and adaptiveThresholdSize must not be even numbers
    int blurSize = 9;
    int blurSTDev = 3;
    int adaptiveThresholdSize = Math.round(mBoxSize * 3); // (oddness ensured below)
    int adaptiveThresholdC = 4; // value to add to the mean (can be negative or zero)
    adaptiveThresholdSize = adaptiveThresholdSize % 2 == 0 ? adaptiveThresholdSize + 1 : adaptiveThresholdSize;

    // how similar the recognised polygon must be to its actual contour - lower is more similar
    float outerPolygonSimilarity = 0.045f;
    float innerPolygonSimilarity = 0.075f; // don't require as much accuracy for the inner part of the tick box

    // how large the maximum internal angle can be (e.g., for checking square shape)
    float maxOuterAngleCos = 0.3f;
    float maxInnerAngleCos = 0.4f;

    // use OpenCV to recognise boxes that have a box inside them - i.e. an un-ticked tick box
    // see: http://stackoverflow.com/a/11427501
    // Bitmap newBitmap = mBitmap.copy(Bitmap.Config.RGB_565, true); // not needed
    Mat bitMat = new Mat();
    Utils.bitmapToMat(mBitmap, bitMat);/*  w  ww.  j a v a2  s . c o  m*/

    // blur and convert to grey
    // alternative (less flexible): Imgproc.medianBlur(bitMat, bitMat, blurSize);
    Imgproc.GaussianBlur(bitMat, bitMat, new Size(blurSize, blurSize), blurSTDev, blurSTDev);
    Imgproc.cvtColor(bitMat, bitMat, Imgproc.COLOR_RGB2GRAY); // need 8uC1 (1 channel, unsigned char) image type

    // perform adaptive thresholding to detect edges
    // alternative (slower): Imgproc.Canny(bitMat, bitMat, 10, 20, 3, false);
    Imgproc.adaptiveThreshold(bitMat, bitMat, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY,
            adaptiveThresholdSize, adaptiveThresholdC);

    // get the contours in the image, and their hierarchy
    Mat hierarchyMat = new Mat();
    List<MatOfPoint> contours = new ArrayList<>();
    Imgproc.findContours(bitMat, contours, hierarchyMat, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);
    if (DEBUG) {
        Imgproc.drawContours(bitMat, contours, -1, new Scalar(30, 255, 255), 1);
    }

    // parse the contours and look for a box containing another box, with similar enough sizes
    int numContours = contours.size();
    ArrayList<Integer> searchedContours = new ArrayList<>();
    Log.d(TAG, "Found " + numContours + " possible tick box areas");
    if (numContours > 0 && !hierarchyMat.empty()) {
        for (int i = 0; i < numContours; i++) {

            // the original detected contour
            MatOfPoint boxPoints = contours.get(i);

            // hierarchy key: 0 = next sibling num, 1 = previous sibling num, 2 = first child num, 3 = parent num
            int childBox = (int) hierarchyMat.get(0, i)[2]; // usually the largest child (as we're doing RETR_TREE)
            if (childBox == -1) { // we only want elements that have children
                continue;
            } else {
                if (searchedContours.contains(childBox)) {
                    if (DEBUG) {
                        Log.d(TAG, "Ignoring duplicate box at first stage: " + childBox);
                    }
                    continue;
                } else {
                    searchedContours.add(childBox);
                }
            }

            // discard smaller (i.e. noise) outer box areas as soon as possible for speed
            // used to do Imgproc.isContourConvex(outerPoints) later, but the angle check covers this, so no need
            double originalArea = Math.abs(Imgproc.contourArea(boxPoints));
            if (originalArea < minimumOuterBoxArea) {
                // if (DEBUG) {
                // drawPoints(bitMat, boxPoints, new Scalar(255, 255, 255), 1);
                // Log.d(TAG, "Outer box too small");
                // }
                continue;
            }
            if (originalArea > maximumOuterBoxArea) {
                // if (DEBUG) {
                // drawPoints(bitMat, boxPoints, new Scalar(255, 255, 255), 1);
                // Log.d(TAG, "Outer box too big");
                // }
                continue;
            }

            // simplify the contours of the outer box - we want to detect four-sided shapes only
            MatOfPoint2f boxPoints2f = new MatOfPoint2f(boxPoints.toArray()); // Point2f for approxPolyDP
            Imgproc.approxPolyDP(boxPoints2f, boxPoints2f,
                    outerPolygonSimilarity * Imgproc.arcLength(boxPoints2f, true), true); // simplify the contour
            if (boxPoints2f.height() != 4) { // height is number of points
                if (DEBUG) {
                    // drawPoints(bitMat, new MatOfPoint(boxPoints2f.toArray()), new Scalar(255, 255, 255), 1);
                    Log.d(TAG, "Outer box not 4 points");
                }
                continue;
            }

            // check that the simplified outer box is approximately a square, angle-wise
            org.opencv.core.Point[] boxPointsArray = boxPoints2f.toArray();
            double maxCosine = 0;
            for (int j = 0; j < 4; j++) {
                org.opencv.core.Point pL = boxPointsArray[j];
                org.opencv.core.Point pIntersect = boxPointsArray[(j + 1) % 4];
                org.opencv.core.Point pR = boxPointsArray[(j + 2) % 4];
                getLineAngle(pL, pIntersect, pR);
                maxCosine = Math.max(maxCosine, getLineAngle(pL, pIntersect, pR));
            }
            if (maxCosine > maxOuterAngleCos) {
                if (DEBUG) {
                    // drawPoints(bitMat, new MatOfPoint(boxPoints2f.toArray()), new Scalar(255, 255, 255), 1);
                    Log.d(TAG, "Outer angles not square enough");
                }
                continue;
            }

            // check that the simplified outer box is approximately a square, line length-wise
            double minLine = Double.MAX_VALUE;
            double maxLine = 0;
            for (int p = 1; p < 4; p++) {
                org.opencv.core.Point p1 = boxPointsArray[p - 1];
                org.opencv.core.Point p2 = boxPointsArray[p];
                double xd = p1.x - p2.x;
                double yd = p1.y - p2.y;
                double lineLength = Math.sqrt((xd * xd) + (yd * yd));
                minLine = Math.min(minLine, lineLength);
                maxLine = Math.max(maxLine, lineLength);
            }
            if (maxLine - minLine > minLine) {
                if (DEBUG) {
                    // drawPoints(bitMat, new MatOfPoint(boxPoints2f.toArray()), new Scalar(255, 255, 255), 1);
                    Log.d(TAG, "Outer lines not square enough");
                }
                continue;
            }

            // draw the outer box if debugging
            if (DEBUG) {
                MatOfPoint debugBoxPoints = new MatOfPoint(boxPointsArray);
                Log.d(TAG,
                        "Potential tick box: " + boxPoints2f.size() + ", " + "area: "
                                + Math.abs(Imgproc.contourArea(debugBoxPoints)) + " (min:" + minimumOuterBoxArea
                                + ", max:" + maximumOuterBoxArea + ")");
                drawPoints(bitMat, debugBoxPoints, new Scalar(50, 255, 255), 2);
            }

            // loop through the children - they should be in descending size order, but sometimes this is wrong
            boolean wrongBox = false;
            while (true) {
                if (DEBUG) {
                    Log.d(TAG, "Looping with box: " + childBox);
                }

                // we've previously tried a child - try the next one
                // key: 0 = next sibling num, 1 = previous sibling num, 2 = first child num, 3 = parent num
                if (wrongBox) {
                    childBox = (int) hierarchyMat.get(0, childBox)[0];
                    if (childBox == -1) {
                        break;
                    }
                    if (searchedContours.contains(childBox)) {
                        if (DEBUG) {
                            Log.d(TAG, "Ignoring duplicate box at loop stage: " + childBox);
                        }
                        break;
                    } else {
                        searchedContours.add(childBox);
                    }
                    //noinspection UnusedAssignment
                    wrongBox = false;
                }

                // perhaps this is the outer box - check its child has no children itself
                // (removed so tiny children (i.e. noise) don't mean we mis-detect an un-ticked box as ticked)
                // if (hierarchyMat.get(0, childBox)[2] != -1) {
                // continue;
                // }

                // check the size of the child box is large enough
                boxPoints = contours.get(childBox);
                originalArea = Math.abs(Imgproc.contourArea(boxPoints));
                if (originalArea < minimumInnerBoxArea) {
                    if (DEBUG) {
                        // drawPoints(bitMat, boxPoints, new Scalar(255, 255, 255), 1);
                        Log.d(TAG, "Inner box too small");
                    }
                    wrongBox = true;
                    continue;
                }

                // simplify the contours of the inner box - again, we want four-sided shapes only
                boxPoints2f = new MatOfPoint2f(boxPoints.toArray());
                Imgproc.approxPolyDP(boxPoints2f, boxPoints2f,
                        innerPolygonSimilarity * Imgproc.arcLength(boxPoints2f, true), true);
                if (boxPoints2f.height() != 4) { // height is number of points
                    // if (DEBUG) {
                    // drawPoints(bitMat, boxPoints, new Scalar(255, 255, 255), 1);
                    // }
                    Log.d(TAG, "Inner box fewer than 4 points"); // TODO: allow > 4 for low quality images?
                    wrongBox = true;
                    continue;
                }

                // check that the simplified inner box is approximately a square, angle-wise
                // higher tolerance because noise means if we get several inners, the box may not be quite square
                boxPointsArray = boxPoints2f.toArray();
                maxCosine = 0;
                for (int j = 0; j < 4; j++) {
                    org.opencv.core.Point pL = boxPointsArray[j];
                    org.opencv.core.Point pIntersect = boxPointsArray[(j + 1) % 4];
                    org.opencv.core.Point pR = boxPointsArray[(j + 2) % 4];
                    getLineAngle(pL, pIntersect, pR);
                    maxCosine = Math.max(maxCosine, getLineAngle(pL, pIntersect, pR));
                }
                if (maxCosine > maxInnerAngleCos) {
                    Log.d(TAG, "Inner angles not square enough");
                    wrongBox = true;
                    continue;
                }

                // this is probably an inner box - log if debugging
                if (DEBUG) {
                    Log.d(TAG,
                            "Un-ticked inner box: " + boxPoints2f.size() + ", " + "area: "
                                    + Math.abs(Imgproc.contourArea(new MatOfPoint2f(boxPointsArray)))
                                    + " (min: " + minimumInnerBoxArea + ")");
                }

                // find the inner box centre
                double centreX = (boxPointsArray[0].x + boxPointsArray[1].x + boxPointsArray[2].x
                        + boxPointsArray[3].x) / 4f;
                double centreY = (boxPointsArray[0].y + boxPointsArray[1].y + boxPointsArray[2].y
                        + boxPointsArray[3].y) / 4f;

                // draw the inner box if debugging
                if (DEBUG) {
                    drawPoints(bitMat, new MatOfPoint(boxPointsArray), new Scalar(255, 255, 255), 1);
                    Core.circle(bitMat, new org.opencv.core.Point(centreX, centreY), 3,
                            new Scalar(255, 255, 255));
                }

                // add to the list of boxes to check
                centrePoints.add(new PointF((float) centreX, (float) centreY));
                break;
            }
        }
    }

    Log.d(TAG, "Found " + centrePoints.size() + " un-ticked boxes");
    return centrePoints;
}

From source file:carmelo.JavaFXOpenCV.java

private Mat procesarImagen(Mat src) {
    Mat dst = new Mat();

    Imgproc.cvtColor(src, dst, Imgproc.COLOR_BGR2GRAY);
    Imgproc.GaussianBlur(dst, dst, new Size(7, 7), 1.5, 1.5);
    Imgproc.Canny(dst, dst, 0, 30, 3, false);

    return dst;//from  w ww . j ava  2s  .  c om
}

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 w  w w.j  a  v  a  2s . co 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

}

From source file:com.example.thibautg.libreaudioview.VideoProcessing.java

License:Open Source License

/**
 *
 * @param data/*from   w  w w . jav a  2  s  . c  o m*/
 */
public void processFrame(byte[] data) {

    int detectionThreshold = 50;
    mInputMat320240.put(0, 0, data);

    mInputGray320240 = mInputMat320240.submat(0, mInputMat320240.height() * 2 / 3, 0, mInputMat320240.width());
    Imgproc.resize(mInputGray320240, mInputGray, new Size(160, 120));

    //mInputMat.put(0, 0, data);
    //mInputGray = mInputMat.submat(0, mInputMat.height() * 2 / 3, 0, mInputMat.width());
    Imgproc.GaussianBlur(mInputGray, mInputGray, windowSize, 0.6, 0.6);
    Core.absdiff(mInputGray, mPreviousMat, mDiffMat2);
    mInputGray.copyTo(mPreviousMat);
    Imgproc.threshold(mDiffMat2, mOutputGrayMat, detectionThreshold, 255, 0);

    if (mBoolFirstImage) {
        mOutputGrayMat.setTo(new Scalar(0));
        mBoolFirstImage = false;
    }

    mSonifier.sonifyFrame(mOutputGrayMat);
}

From source file:com.louislepper.waveform.MainActivity.java

License:Apache License

@Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
    Mat currentMat = inputFrame.rgba();//from  w  w w . j  a  va 2 s  .  co m

    Imgproc.cvtColor(currentMat, currentMat, Imgproc.COLOR_RGBA2GRAY);
    Imgproc.GaussianBlur(currentMat, currentMat, new Size(5, 5), 2, 2);
    Imgproc.threshold(currentMat, currentMat, LIGHT_THRESH, LIGHT_THRESH, Imgproc.THRESH_TRUNC);
    Imgproc.GaussianBlur(currentMat, currentMat, new Size(5, 5), 2, 2);
    Imgproc.GaussianBlur(currentMat, currentMat, new Size(9, 9), 0, 0);
    Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(5, 5));
    Imgproc.dilate(currentMat, currentMat, kernel);

    //Canny edge detection
    Imgproc.Canny(currentMat, currentMat, CANNY_LOW, CANNY_HIGH);

    if (soundData == null || soundData.length != currentMat.cols()) {
        soundData = new short[currentMat.cols()];
    }

    imageArrayToSoundArray(new ArrayMat(currentMat), soundData);

    SampleInterpolator.StartAndEnd startAndEnd = SampleInterpolator.interpolateInvalidSamples(soundData);

    if (smoothing) {
        soundData = SampleCrossfader.crossfade(soundData, startAndEnd.getStart(), startAndEnd.getLength());
    }

    if (audioThread == null || !audioThread.isAlive()) {
        audioThread = new AudioThread();
        keyboardView.setMidiListener(audioThread);
        //This should maybe get its value from preferences. Not sure if number picker will have been set in time.
        audioThread.setOctave(numberPicker.getValue());
        if (currentScreen.equals(KEYBOARD)) {
            audioThread.keyboardOn();
        } else {
            audioThread.keyboardOff();
        }
        audioThread.start();
    }

    //Send array here.
    audioThread.setWaveform(soundData, startAndEnd);

    if (lineFeedback) {
        Imgproc.cvtColor(currentMat, currentMat, Imgproc.COLOR_GRAY2RGBA);

        soundArrayToImage(soundData, currentMat);
    }

    return currentMat;
}

From source file:com.trandi.opentld.tld.PatchGenerator.java

License:Apache License

/**
 * //from   w w  w . ja  v a 2s  .  c o m
 * @param image
 * @param T
 * @param patch OUTPUT
 * @param patchSize
 */
void generate(final Mat image, final Mat T, Mat patch, Size patchSize, final RNG rng) {
    patch.create(patchSize, image.type());
    if (backgroundMin != backgroundMax) {
        Core.randu(patch, backgroundMin, backgroundMax);
        // TODO if that null scalar OK or should it be new Scalar(0) ?
        Imgproc.warpAffine(image, patch, T, patchSize, Imgproc.INTER_LINEAR, Core.BORDER_TRANSPARENT, null);
    } else {
        Imgproc.warpAffine(image, patch, T, patchSize, Imgproc.INTER_LINEAR, Core.BORDER_CONSTANT,
                new Scalar(backgroundMin));
    }

    int ksize = randomBlur ? rng.nextInt() % 9 - 5 : 0;
    if (ksize > 0) {
        ksize = ksize * 2 + 1;
        Imgproc.GaussianBlur(patch, patch, new Size(ksize, ksize), 0, 0);
    }

    if (noiseRange > 0) {
        final Mat noise = new Mat(patchSize, image.type());
        int delta = (image.depth() == CvType.CV_8U ? 128 : (image.depth() == CvType.CV_16U ? 32768 : 0));
        Core.randn(noise, delta, noiseRange);

        // TODO this was different !!
        Core.addWeighted(patch, 1, noise, 1, -delta, patch);

        //           if( backgroundMin != backgroundMax )
        //               addWeighted(patch, 1, noise, 1, -delta, patch);
        //           else
        //           {
        //               for( int i = 0; i < patchSize.height; i++ )
        //               {
        //                   uchar* prow = patch.ptr<uchar>(i);
        //                   const uchar* nrow =  noise.ptr<uchar>(i);
        //                   for( int j = 0; j < patchSize.width; j++ )
        //                       if( prow[j] != backgroundMin )
        //                           prow[j] = saturate_cast<uchar>(prow[j] + nrow[j] - delta);
        //               }
        //           }
    }
}

From source file:com.untref.bordes.HoughCirculos.java

public static BufferedImage implementarCiculos(BufferedImage screen, int acumulador, int radioMin,
        int radioMax) {
    Mat source = new Mat(screen.getHeight(), screen.getWidth(), CvType.CV_8UC3);
    byte[] data = ((DataBufferByte) screen.getRaster().getDataBuffer()).getData();
    source.put(0, 0, data);//from  ww w .j  a  v a 2 s .co m
    //ImageIO.write(screen, "jpg", "imagen");
    //Mat source = Highgui.imread("test.jpg", Highgui.CV_LOAD_IMAGE_COLOR);
    Mat destination = new Mat(source.rows(), source.cols(), source.type());

    Imgproc.cvtColor(source, destination, Imgproc.COLOR_RGB2GRAY);

    Imgproc.GaussianBlur(destination, destination, new Size(3, 3), 0, 0);

    Mat circles = new Mat();
    Imgproc.HoughCircles(destination, circles, Imgproc.CV_HOUGH_GRADIENT, 1, 30, 10, acumulador, radioMin,
            radioMax);

    int radius;
    org.opencv.core.Point pt;
    for (int x = 0; x < circles.cols(); x++) {
        double vCircle[] = circles.get(0, x);

        if (vCircle == null) {
            break;
        }

        pt = new org.opencv.core.Point(Math.round(vCircle[0]), Math.round(vCircle[1]));
        radius = (int) Math.round(vCircle[2]);

        // draw the found circle
        Core.circle(source, pt, radius, new Scalar(150, 0, 0), 2);
        Core.circle(source, pt, 1, new Scalar(0, 0, 0), 2);
    }
    BufferedImage res = matToBufferedImage(source);

    return res;

}