Example usage for org.opencv.core Mat setTo

List of usage examples for org.opencv.core Mat setTo

Introduction

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

Prototype

public Mat setTo(Mat value) 

Source Link

Usage

From source file:com.mitzuli.core.ocr.OcrPreprocessor.java

License:Open Source License

/**
 * Binarizes and cleans the input image for OCR, saving debugging images in the given directory.
 *
 * @param input the input image, which is recycled by this method, so the caller should make a defensive copy of it if necessary.
 * @param debugDir the directory to write the debugging images to, or null to disable debugging.
 * @return the preprocessed image.//from  www .  j a  v a  2s. com
 */
static Image preprocess(final Image input, final File debugDir) {
    // TODO Temporary workaround to allow to manually enable debugging (the global final variable should be used)
    boolean DEBUG = debugDir != null;

    // Initialization
    final Mat mat = input.toGrayscaleMat();
    final Mat debugMat = DEBUG ? input.toRgbMat() : null;
    input.recycle();
    final Mat aux = new Mat(mat.size(), CvType.CV_8UC1);
    final Mat binary = new Mat(mat.size(), CvType.CV_8UC1);
    if (DEBUG)
        Image.fromMat(mat).write(new File(debugDir, "1_input.jpg"));

    // Binarize the input image in mat through adaptive Gaussian thresholding
    Imgproc.adaptiveThreshold(mat, binary, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 51,
            13);
    // Imgproc.adaptiveThreshold(mat, binary, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 31, 7);

    // Edge detection
    Imgproc.morphologyEx(mat, mat, Imgproc.MORPH_OPEN, KERNEL_3X3); // Open
    Imgproc.morphologyEx(mat, aux, Imgproc.MORPH_CLOSE, KERNEL_3X3); // Close
    Core.addWeighted(mat, 0.5, aux, 0.5, 0, mat); // Average
    Imgproc.morphologyEx(mat, mat, Imgproc.MORPH_GRADIENT, KERNEL_3X3); // Gradient
    Imgproc.threshold(mat, mat, 0, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU); // Edge map
    if (DEBUG)
        Image.fromMat(mat).write(new File(debugDir, "2_edges.jpg"));

    // Extract word level connected-components from the dilated edge map
    Imgproc.dilate(mat, mat, KERNEL_3X3);
    if (DEBUG)
        Image.fromMat(mat).write(new File(debugDir, "3_dilated_edges.jpg"));
    final List<MatOfPoint> wordCCs = new ArrayList<MatOfPoint>();
    Imgproc.findContours(mat, wordCCs, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    // Filter word level connected-components individually and calculate their average attributes
    final List<MatOfPoint> individuallyFilteredWordCCs = new ArrayList<MatOfPoint>();
    final List<MatOfPoint> removedWordCCs = new ArrayList<MatOfPoint>();
    double avgWidth = 0, avgHeight = 0, avgArea = 0;
    for (MatOfPoint cc : wordCCs) {
        final Rect boundingBox = Imgproc.boundingRect(cc);
        if (boundingBox.height >= 6 // bounding box height >= 6
                && boundingBox.area() >= 50 // bounding box area >= 50
                && (double) boundingBox.width / (double) boundingBox.height >= 0.25 // bounding box aspect ratio >= 1:4
                && boundingBox.width <= 0.75 * mat.width() // bounding box width <= 0.75 image width
                && boundingBox.height <= 0.75 * mat.height()) // bounding box height <= 0.75 image height
        {
            individuallyFilteredWordCCs.add(cc);
            avgWidth += boundingBox.width;
            avgHeight += boundingBox.height;
            avgArea += boundingBox.area();
        } else {
            if (DEBUG)
                removedWordCCs.add(cc);
        }
    }
    wordCCs.clear();
    avgWidth /= individuallyFilteredWordCCs.size();
    avgHeight /= individuallyFilteredWordCCs.size();
    avgArea /= individuallyFilteredWordCCs.size();
    if (DEBUG) {
        Imgproc.drawContours(debugMat, removedWordCCs, -1, BLUE, -1);
        removedWordCCs.clear();
    }

    // Filter word level connected-components in relation to their average attributes
    final List<MatOfPoint> filteredWordCCs = new ArrayList<MatOfPoint>();
    for (MatOfPoint cc : individuallyFilteredWordCCs) {
        final Rect boundingBox = Imgproc.boundingRect(cc);
        if (boundingBox.width >= 0.125 * avgWidth // bounding box width >= 0.125 average width
                && boundingBox.width <= 8 * avgWidth // bounding box width <= 8 average width
                && boundingBox.height >= 0.25 * avgHeight // bounding box height >= 0.25 average height
                && boundingBox.height <= 4 * avgHeight) // bounding box height <= 4 average height
        {
            filteredWordCCs.add(cc);
        } else {
            if (DEBUG)
                removedWordCCs.add(cc);
        }
    }
    individuallyFilteredWordCCs.clear();
    if (DEBUG) {
        Imgproc.drawContours(debugMat, filteredWordCCs, -1, GREEN, -1);
        Imgproc.drawContours(debugMat, removedWordCCs, -1, PURPLE, -1);
        removedWordCCs.clear();
    }

    // Extract paragraph level connected-components
    mat.setTo(BLACK);
    Imgproc.drawContours(mat, filteredWordCCs, -1, WHITE, -1);
    final List<MatOfPoint> paragraphCCs = new ArrayList<MatOfPoint>();
    Imgproc.morphologyEx(mat, aux, Imgproc.MORPH_CLOSE, KERNEL_30X30);
    Imgproc.findContours(aux, paragraphCCs, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    // Filter paragraph level connected-components according to the word level connected-components inside
    final List<MatOfPoint> textCCs = new ArrayList<MatOfPoint>();
    for (MatOfPoint paragraphCC : paragraphCCs) {
        final List<MatOfPoint> wordCCsInParagraphCC = new ArrayList<MatOfPoint>();
        aux.setTo(BLACK);
        Imgproc.drawContours(aux, Collections.singletonList(paragraphCC), -1, WHITE, -1);
        Core.bitwise_and(mat, aux, aux);
        Imgproc.findContours(aux, wordCCsInParagraphCC, new Mat(), Imgproc.RETR_EXTERNAL,
                Imgproc.CHAIN_APPROX_SIMPLE);
        final Rect boundingBox = Imgproc.boundingRect(paragraphCC);
        final double center = mat.size().width / 2;
        final double distToCenter = center > boundingBox.x + boundingBox.width
                ? center - boundingBox.x - boundingBox.width
                : center < boundingBox.x ? boundingBox.x - center : 0.0;
        if (DEBUG) {
            System.err.println("****************************************");
            System.err.println("\tArea:                " + boundingBox.area());
            System.err.println("\tDistance to center:  " + distToCenter);
            System.err.println("\tCCs inside:          " + wordCCsInParagraphCC.size());
        }
        if ((wordCCsInParagraphCC.size() >= 10 || wordCCsInParagraphCC.size() >= 0.3 * filteredWordCCs.size())
                && mat.size().width / distToCenter >= 4) {
            textCCs.addAll(wordCCsInParagraphCC);
            if (DEBUG) {
                System.err.println("\tText:                YES");
                Imgproc.drawContours(debugMat, Collections.singletonList(paragraphCC), -1, DARK_GREEN, 5);
            }
        } else {
            if (DEBUG) {
                System.err.println("\tText:                NO");
                Imgproc.drawContours(debugMat, Collections.singletonList(paragraphCC), -1, DARK_RED, 5);
            }
        }
    }
    filteredWordCCs.clear();
    paragraphCCs.clear();
    mat.setTo(WHITE);
    Imgproc.drawContours(mat, textCCs, -1, BLACK, -1);
    textCCs.clear();
    if (DEBUG)
        Image.fromMat(debugMat).write(new File(debugDir, "4_filtering.jpg"));

    // Obtain the final text mask from the filtered connected-components
    Imgproc.erode(mat, mat, KERNEL_15X15);
    Imgproc.morphologyEx(mat, mat, Imgproc.MORPH_OPEN, KERNEL_30X30);
    if (DEBUG)
        Image.fromMat(mat).write(new File(debugDir, "5_text_mask.jpg"));

    // Apply the text mask to the binarized image
    if (DEBUG)
        Image.fromMat(binary).write(new File(debugDir, "6_binary.jpg"));
    binary.setTo(WHITE, mat);
    if (DEBUG)
        Image.fromMat(binary).write(new File(debugDir, "7_binary_text.jpg"));

    // Dewarp the text using Leptonica
    Pix pixs = Image.fromMat(binary).toGrayscalePix();
    Pix pixsDewarp = Dewarp.dewarp(pixs, 0, Dewarp.DEFAULT_SAMPLING, 5, true);
    final Image result = Image.fromGrayscalePix(pixsDewarp);
    if (DEBUG)
        result.write(new File(debugDir, "8_dewarp.jpg"));

    // Clean up
    pixs.recycle();
    mat.release();
    aux.release();
    binary.release();
    if (debugMat != null)
        debugMat.release();

    return result;
}

From source file:com.projecttango.examples.java.pointcloud.MainActivity.java

License:Open Source License

/**
 * Set up the callback listeners for the Tango Service and obtain other parameters required
 * after Tango connection./*from w w  w .j a  va2s.co  m*/
 * Listen to updates from the Point Cloud and Tango Events and Pose.
 */
private void startupTango() {
    final ArrayList<TangoCoordinateFramePair> framePairs = new ArrayList<TangoCoordinateFramePair>();

    framePairs.add(new TangoCoordinateFramePair(TangoPoseData.COORDINATE_FRAME_START_OF_SERVICE,
            TangoPoseData.COORDINATE_FRAME_DEVICE));

    mTango.connectListener(framePairs, new Tango.TangoUpdateCallback() {
        @Override
        public void onPoseAvailable(TangoPoseData pose) {
            // Passing in the pose data to UX library produce exceptions.
            if (mTangoUx != null) {
                mTangoUx.updatePoseStatus(pose.statusCode);
            }

            mapPos = pose;

            /*
            TANGO POSE UPDATE FOR MAP HERE
                    
             */

            //mapInfo.setCurrentCell(pose);
        }

        @Override
        public void onPointCloudAvailable(TangoPointCloudData pointCloud) {
            if (mTangoUx != null) {
                mTangoUx.updatePointCloud(pointCloud);
            }
            mPointCloudManager.updatePointCloud(pointCloud);

            final double currentTimeStamp = pointCloud.timestamp;
            final double pointCloudFrameDelta = (currentTimeStamp - mPointCloudPreviousTimeStamp)
                    * SECS_TO_MILLISECS;
            mPointCloudPreviousTimeStamp = currentTimeStamp;
            final double averageDepth = getAveragedDepth(pointCloud.points, pointCloud.numPoints);

            mPointCloudTimeToNextUpdate -= pointCloudFrameDelta;

            if (mPointCloudTimeToNextUpdate < 0.0) {
                mPointCloudTimeToNextUpdate = UPDATE_INTERVAL_MS;
                final String pointCountString = Integer.toString(pointCloud.numPoints);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //mPointCountTextView.setText(pointCountString);
                        //mAverageZTextView.setText(FORMAT_THREE_DECIMAL.format(averageDepth));
                    }
                });
            }
        }

        @Override
        public void onFrameAvailable(int cameraId) {
            // We are not using onFrameAvailable for this application.
            if (cameraId == TangoCameraIntrinsics.TANGO_CAMERA_COLOR) {
                tangoCameraPreview.onFrameAvailable();
                bm[0] = tangoCameraPreview.getBitmap();
                frameCount++;
                Log.d("FPSTango", ": " + frameCount);
                Bitmap openCVBitmap = tangoCameraPreview.getBitmap();
                tmp = new Mat(openCVBitmap.getWidth(), openCVBitmap.getHeight(), CvType.CV_8UC4);
                mDetector.process(tmp);
                ////////////////////////

                List<MatOfPoint> contours = mDetector.getContours();
                // Log.e("rescue robotics", "Contours count: " + contours.size());
                Imgproc.drawContours(tmp, contours, -1, CONTOUR_COLOR);

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

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

                if (mDetector.blobsDetected() > 0) {
                    toast("I see a Blob!");
                }
                if (frameCount == 30) {
                    frameCount = 0;
                    scan(tangoCameraPreview.getBitmap());

                }
            }
        }

        @Override
        public void onTangoEvent(TangoEvent event) {
            if (mTangoUx != null) {
                mTangoUx.updateTangoEvent(event);
            }
        }
    });
}

From source file:cv.recon.util.CannyDetector.java

License:Open Source License

/**
 * Apply Canny detector to Mat.//from   w w w  .  ja va 2s . co  m
 * @param src Input Mat
 * @param dst Output Mat
 */
public void detect(Mat src, Mat dst) {
    Mat src_gray = new Mat();
    Mat detected_edges = new Mat();

    Imgproc.cvtColor(src, src_gray, Imgproc.COLOR_RGB2GRAY);
    Imgproc.blur(src_gray, detected_edges, new Size(3, 3));
    Imgproc.Canny(detected_edges, detected_edges, lowThreshold, lowThreshold * ratio, kernel_size, true);

    dst.setTo(new Scalar(0));
    src.copyTo(dst, detected_edges);
}

From source file:info.jmfavreau.bifrostcore.imageprocessing.ImageToColor.java

License:Open Source License

private Mat compute_roi(Mat original) {
    Mat roi = new Mat();
    Imgproc.cvtColor(original, roi, Imgproc.COLOR_BGR2GRAY, 0);
    roi.setTo(new Scalar(0, 0, 0));
    int x = original.width();
    int y = original.height();
    int cx = x / 2;
    int cy = y / 2;
    int r = Math.min(cx, cy) * 2 / 3;
    Core.circle(roi, new Point(cx, cy), r, new Scalar(255, 255, 255), -1, 8, 0);
    return roi;/*from ww w  .  j a  va 2  s .c o m*/
}

From source file:javaapplication1.JavaApplication1.java

public static void main(String[] args) {
    // you must load the OpenCV library like this before trying to do
    // anything with OpenCV!
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    // Print OpenCV version
    System.out.println("Welcome to OpenCV " + Core.VERSION);

    // In OpenCV, the most important data type is the Matrix, Mat.
    ////from  ww  w  .  ja  va 2s  . c o  m
    // Here, we create a matrix that has 5 rows and 10 columns.  It
    // stores an 8-bit type with a single channel.  In other words, a
    // matrix of bytes.  We'll initialize every element to 0.
    Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));

    // Dump information about the matrix
    System.out.println("OpenCV Mat: " + m);

    // set row 1 to be all 1s, and then column 5 to be all 5s
    Mat mr1 = m.row(1);
    mr1.setTo(new Scalar(1));
    Mat mc5 = m.col(5);
    mc5.setTo(new Scalar(5));

    // Dump the actual matrix contents
    System.out.println("OpenCV Mat data:\n" + m.dump());

    Ocv ocv = new Ocv();
    ocv.getFilePath();

    /**
     * Find faces in an image.
     *
     * @param filter Path to the xml face finding filter to use
     * @param input Path to the input image file
     * @param output Path to the output image file
     */
    //ocv.findFaces("lbpcascade_frontalface.xml", "C:\\Users\\Wellesley\\Documents\\GitHub\\CSE398\\opencvTutorial\\JavaApplication1\\src\\javaapplication1\\lena.png", "../javaapplication1");
    ocv.setOutput("step2.png");
    ocv.findFaces("", "", "");
    ocv.setOutput("step3.png");
    ocv.cropEachFace("", "");
    ocv.setOutput("step4.png");
    ocv.resizeEachFace("", "");
    ocv.setOutput("step6.png");
    ocv.makeFacesGray("", "", "");
    ocv.setOutput("step8.png");
    ocv.blendWithGray50("", "");
    ocv.setOutput("step10.png");
    ocv.doSobel("", "");
    ocv.setOutput("step11.png");
    ocv.directManip("", "");
}

From source file:karthik.Barcode.CandidateMatrixBarcode.java

License:Open Source License

CandidateResult NormalizeCandidateRegion(double angle) {
    /* candidateRegion is the RotatedRect which contains a candidate region for the barcode
     // angle is the rotation angle or USE_ROTATED_RECT_ANGLE for this function to 
     // estimate rotation angle from the rect parameter
     // returns Mat containing cropped area(region of interest) with just the barcode 
     // The barcode region is from the *original* image, not the scaled image
     // the cropped area is also rotated as necessary to be horizontal or vertical rather than skewed        
     // Some parts of this function are from http://felix.abecassis.me/2011/10/opencv-rotation-deskewing/
     // and http://stackoverflow.com/questions/22041699/rotate-an-image-without-cropping-in-opencv-in-c
     *///from www.j av a2 s.c  o  m

    double rotation_angle;
    CandidateResult result = new CandidateResult();

    // scale candidate region back up to original size to return cropped part from *original* image 
    // need the 1.0 there to force floating-point arithmetic from int values
    double scale_factor = img_details.src_original.rows() / (1.0 * img_details.src_grayscale.rows());

    // expand the region found - this helps capture the entire code including the border zone
    candidateRegion.size.width += 2 * params.RECT_WIDTH;
    candidateRegion.size.height += 2 * params.RECT_HEIGHT;

    // calculate location of rectangle in original image and its corner points
    RotatedRect scaledRegion = new RotatedRect(candidateRegion.center, candidateRegion.size,
            candidateRegion.angle);
    scaledRegion.center.x = scaledRegion.center.x * scale_factor;
    scaledRegion.center.y = scaledRegion.center.y * scale_factor;
    scaledRegion.size.height *= scale_factor;
    scaledRegion.size.width *= scale_factor;

    scaledRegion.points(img_details.scaledCorners);
    // lets get the coordinates of the ROI in the original image and save it

    result.ROI_coords = Arrays.copyOf(img_details.scaledCorners, 4);

    // get the bounding rectangle of the ROI by sorting its corner points
    // we do it manually because RotatedRect can generate corner points outside the Mat area
    Arrays.sort(img_details.scaledCorners, CandidateBarcode.get_x_comparator());
    int leftCol = (int) img_details.scaledCorners[0].x;
    int rightCol = (int) img_details.scaledCorners[3].x;
    leftCol = (leftCol < 0) ? 0 : leftCol;
    rightCol = (rightCol > img_details.src_original.cols() - 1) ? img_details.src_original.cols() - 1
            : rightCol;

    Arrays.sort(img_details.scaledCorners, CandidateBarcode.get_y_comparator());
    int topRow = (int) img_details.scaledCorners[0].y;
    int bottomRow = (int) img_details.scaledCorners[3].y;
    topRow = (topRow < 0) ? 0 : topRow;
    bottomRow = (bottomRow > img_details.src_original.rows() - 1) ? img_details.src_original.rows() - 1
            : bottomRow;

    Mat ROI_region = img_details.src_original.submat(topRow, bottomRow, leftCol, rightCol);

    // create a container that is a square with side = diagonal of ROI.
    // this is large enough to accommodate the ROI region with rotation without cropping it

    int orig_rows = bottomRow - topRow;
    int orig_cols = rightCol - leftCol;
    int diagonal = (int) Math.sqrt(orig_rows * orig_rows + orig_cols * orig_cols);

    int newWidth = diagonal + 1;
    int newHeight = diagonal + 1;

    int offsetX = (newWidth - orig_cols) / 2;
    int offsetY = (newHeight - orig_rows) / 2;

    Mat enlarged_ROI_container = new Mat(newWidth, newHeight, img_details.src_original.type());
    enlarged_ROI_container.setTo(ZERO_SCALAR);

    // copy ROI to centre of container and rotate it
    ROI_region.copyTo(enlarged_ROI_container.rowRange(offsetY, offsetY + orig_rows).colRange(offsetX,
            offsetX + orig_cols));
    Point enlarged_ROI_container_centre = new Point(enlarged_ROI_container.rows() / 2.0,
            enlarged_ROI_container.cols() / 2.0);
    Mat rotated = Mat.zeros(enlarged_ROI_container.size(), enlarged_ROI_container.type());

    if (angle == Barcode.USE_ROTATED_RECT_ANGLE)
        rotation_angle = estimate_barcode_orientation();
    else
        rotation_angle = angle;

    // perform the affine transformation
    img_details.rotation_matrix = Imgproc.getRotationMatrix2D(enlarged_ROI_container_centre, rotation_angle,
            1.0);
    img_details.rotation_matrix.convertTo(img_details.rotation_matrix, CvType.CV_32F); // convert type so matrix multip. works properly

    img_details.newCornerCoord.setTo(ZERO_SCALAR);

    // convert scaledCorners to contain locations of corners in enlarged_ROI_container Mat
    img_details.scaledCorners[0] = new Point(offsetX, offsetY);
    img_details.scaledCorners[1] = new Point(offsetX, offsetY + orig_rows);
    img_details.scaledCorners[2] = new Point(offsetX + orig_cols, offsetY);
    img_details.scaledCorners[3] = new Point(offsetX + orig_cols, offsetY + orig_rows);
    // calculate the new location for each corner point of the rectangle ROI after rotation
    for (int r = 0; r < 4; r++) {
        img_details.coord.put(0, 0, img_details.scaledCorners[r].x);
        img_details.coord.put(1, 0, img_details.scaledCorners[r].y);
        Core.gemm(img_details.rotation_matrix, img_details.coord, 1, img_details.delta, 0,
                img_details.newCornerCoord);
        updatePoint(img_details.newCornerPoints.get(r), img_details.newCornerCoord.get(0, 0)[0],
                img_details.newCornerCoord.get(1, 0)[0]);
    }
    rotated.setTo(ZERO_SCALAR);
    Imgproc.warpAffine(enlarged_ROI_container, rotated, img_details.rotation_matrix,
            enlarged_ROI_container.size(), Imgproc.INTER_CUBIC);
    // sort rectangles points in order by first sorting all 4 points based on x
    // we then sort the first two based on y and then the next two based on y
    // this leaves the array in order top-left, bottom-left, top-right, bottom-right
    Collections.sort(img_details.newCornerPoints, CandidateBarcode.get_x_comparator());
    Collections.sort(img_details.newCornerPoints.subList(0, 2), CandidateBarcode.get_y_comparator());
    Collections.sort(img_details.newCornerPoints.subList(2, 4), CandidateBarcode.get_y_comparator());

    // calc height and width of rectangular region

    double height = length(img_details.newCornerPoints.get(1), img_details.newCornerPoints.get(0));
    double width = length(img_details.newCornerPoints.get(2), img_details.newCornerPoints.get(0));

    // create destination points for warpPerspective to map to
    updatePoint(img_details.transformedPoints.get(0), 0, 0);
    updatePoint(img_details.transformedPoints.get(1), 0, height);
    updatePoint(img_details.transformedPoints.get(2), width, 0);
    updatePoint(img_details.transformedPoints.get(3), width, height);

    Mat perspectiveTransform = Imgproc.getPerspectiveTransform(
            Converters.vector_Point2f_to_Mat(img_details.newCornerPoints),
            Converters.vector_Point2f_to_Mat(img_details.transformedPoints));
    Mat perspectiveOut = Mat.zeros((int) height + 2, (int) width + 2, CvType.CV_32F);
    Imgproc.warpPerspective(rotated, perspectiveOut, perspectiveTransform, perspectiveOut.size(),
            Imgproc.INTER_CUBIC);

    result.ROI = perspectiveOut;
    return result;
}

From source file:karthik.Barcode.MatrixBarcode.java

License:Open Source License

private Mat calcProbabilityTilings(int tileSize) {
    // calculates probability of each tile being in a 2D barcode region
    // tiles must be square
    assert (searchParams.RECT_HEIGHT == searchParams.RECT_WIDTH) : "RECT_HEIGHT and RECT_WIDTH must be equal in searchParams imageSpecificParams";

    int probMatTileSize = (int) (tileSize * (searchParams.PROB_MAT_TILE_SIZE / (1.0 * searchParams.tileSize)));
    int threshold_min_gradient_edges = (int) (tileSize * tileSize
            * searchParams.THRESHOLD_MIN_GRADIENT_EDGES_MULTIPLIER);

    int right_col, bottom_row;
    int prob_mat_right_col, prob_mat_bottom_row;

    Mat imgWindow; // used to hold sub-matrices from the image that represent the window around the current point
    Mat prob_window; // used to hold sub-matrices into probability matrix that represent window around current point

    int num_edges;
    double prob;/*from  w  w  w.  j  a v  a  2 s .c om*/
    int max_angle_idx, second_highest_angle_index, max_angle_count, second_highest_angle_count, angle_diff;

    img_details.probabilities.setTo(ZERO_SCALAR);

    for (int i = 0, row_offset = 0; i < rows; i += tileSize, row_offset += probMatTileSize) {
        // first do bounds checking for bottom right of tiles

        bottom_row = java.lang.Math.min((i + tileSize), rows);
        prob_mat_bottom_row = java.lang.Math.min((row_offset + probMatTileSize), img_details.probMatRows);

        for (int j = 0, col_offset = 0; j < cols; j += tileSize, col_offset += probMatTileSize) {

            // then calculate the column locations of the rectangle and set them to -1 
            // if they are outside the matrix bounds                
            right_col = java.lang.Math.min((j + tileSize), cols);
            prob_mat_right_col = java.lang.Math.min((col_offset + probMatTileSize), img_details.probMatCols);

            // calculate number of edges in the tile using the already calculated integral image 
            num_edges = (int) calc_rect_sum(img_details.edgeDensity, img_details.histNumRows,
                    img_details.histNumCols, i, bottom_row, j, right_col);

            if (num_edges < threshold_min_gradient_edges)
                // if gradient density is below the threshold level, prob of matrix code in this tile is 0
                continue;

            for (int r = 0; r < img_details.bins; r++) {

                img_details.histArray[r] = (int) calc_rect_sum(img_details.histIntegralArrays[r],
                        img_details.histNumRows, img_details.histNumCols, i, bottom_row, j, right_col);
            }

            hist = Converters.vector_int_to_Mat(Arrays.asList(img_details.histArray));
            Core.sortIdx(hist, histIdx, Core.SORT_EVERY_COLUMN + Core.SORT_DESCENDING);

            max_angle_idx = (int) histIdx.get(0, 0)[0];
            max_angle_count = (int) hist.get(max_angle_idx, 0)[0];

            second_highest_angle_index = (int) histIdx.get(1, 0)[0];
            second_highest_angle_count = (int) hist.get(second_highest_angle_index, 0)[0];

            angle_diff = Math.abs(max_angle_idx - second_highest_angle_index);

            // formula below is modified from Szentandrasi, Herout, Dubska paper pp. 4
            prob = 0;
            if (angle_diff != 1) // ignores tiles where there is just noise between adjacent bins in the histogram
                prob = 2.0 * Math.min(max_angle_count, second_highest_angle_count)
                        / (max_angle_count + second_highest_angle_count);

            prob_window = img_details.probabilities.submat(row_offset, prob_mat_bottom_row, col_offset,
                    prob_mat_right_col);
            prob_window.setTo(new Scalar((int) (prob * 255)));

        } // for j
    } // for i

    return img_details.probabilities;

}

From source file:karthik.Barcode.MatrixBarcode.java

License:Open Source License

private void calcHistograms() {
    /* calculate histogram by masking for angles inside each bin, thresholding to set all those values to 1
       and then creating an integral image. We can now calculate histograms for any size tile within 
       the original image more efficiently than by using the built in calcHist method which would have to 
       recalculate the histogram for every tile size.
    *///from   www.j  a  v a  2 s .  c  o  m
    Mat target;
    angles = img_details.gradient_direction.clone();
    target = img_details.temp_integral;

    for (int binRange = 1, integralIndex = 0; binRange < 181; binRange += img_details.BIN_WIDTH, integralIndex++) {
        target.setTo(ZERO_SCALAR);

        img_details.gradient_direction.copyTo(angles);
        Core.inRange(img_details.gradient_direction, scalarDict.get(binRange),
                scalarDict.get(binRange + img_details.BIN_WIDTH), mask);
        Core.bitwise_not(mask, mask);
        angles.setTo(ZERO_SCALAR, mask);

        Imgproc.threshold(angles, target, 0, 1, Imgproc.THRESH_BINARY);
        Imgproc.integral(target, target);
        target.get(0, 0, img_details.histIntegralArrays[integralIndex]);
    }

    // there is some problem if the created integral image does not have exactly one channel
    assert (target.channels() == 1) : "Integral does not have exactly one channel";

}

From source file:LetsStart.GUI.java

private void addNoise() {
    image = originalImage.clone();/*from  w  ww . jav  a 2 s.  c om*/
    Mat grayRnd = new Mat(image.rows(), image.cols(), image.type());
    double noise = 128;
    grayRnd.setTo(new Scalar(noise / 2, noise / 2, noise / 2));
    Core.subtract(image, grayRnd, image);
    Core.randu(grayRnd, 0, noise);
    Core.add(image, grayRnd, image);
    processOperation();
    updateView();
}

From source file:logic.imagelocalizator.EyeBrowsLocalizator.java

private boolean detectEyeBrowBoundRect(MatContainer mc) {
    int eyePairW = mc.eyePairRect.width;
    int eyePairH = mc.eyePairRect.height;

    //contains eyebrow bounding rectangles
    Rect boundRectArr[] = new Rect[2];

    //for each eyebrow
    Mat binMat = new Mat();
    for (int i = 0; i < 2; ++i) {
        mc.eyeBrowMatArr[i] = mc.grayFrame.submat(mc.eyeBrowRectArr[i]);
        Scalar meanScalar = Core.mean(mc.eyeBrowMatArr[i]);
        //negate image
        Core.convertScaleAbs(mc.eyeBrowMatArr[i], mc.eyeBrowMatArr[i], 1, 255 - meanScalar.val[0]);
        Imgproc.equalizeHist(mc.eyeBrowMatArr[i], mc.eyeBrowMatArr[i]);
        Imgproc.blur(mc.eyeBrowMatArr[i], mc.eyeBrowMatArr[i], new Size(4, 4));

        //obtain binary image
        Imgproc.threshold(mc.eyeBrowMatArr[i], binMat, 70, 255, Imgproc.THRESH_BINARY_INV);

        Imgproc.morphologyEx(binMat, binMat, Imgproc.MORPH_OPEN,
                Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(4, 4)));

        //find contours
        List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
        Imgproc.findContours(binMat, contours, new Mat(), Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);

        //find the biggest contour
        int maxSize = -1;
        int tmpSize = -1;
        int index = -1;

        if (contours.size() != 0) {
            maxSize = contours.get(0).toArray().length;
            tmpSize = 0;/*  w ww .  ja v  a 2 s.  co m*/
            index = 0;
        }

        //find max contour
        for (int j = 0; j < contours.size(); ++j) {
            //if contour is vertical, exclude it 
            Rect boundRect = Imgproc.boundingRect(contours.get(j));
            if (boundRect.height > boundRect.width)
                continue;

            if ((double) boundRect.height
                    / (double) mc.eyeBrowRectArr[i].height > Parameters.eyebrowBoundRectThresh) {
                LOG.warn("Reset brow rect");
                mc.eyeBrowBoundRectArr[i] = null;
                return false;
            }

            tmpSize = contours.get(j).toArray().length;

            LOG.info("Contour " + j + "; size = " + tmpSize);

            if (tmpSize > maxSize) {
                maxSize = tmpSize;
                index = j;
            }
        }

        binMat.setTo(new Scalar(0));
        boundRectArr[i] = Imgproc.boundingRect(contours.get(index));

        //save eyebrow bounding rectangle
        mc.eyeBrowBoundRectArr[i] = new Rect(mc.eyeBrowRectArr[i].x + boundRectArr[i].x,
                mc.eyeBrowRectArr[i].y + boundRectArr[i].y, boundRectArr[i].width, boundRectArr[i].height);

        //save binary eyebrow Mat for further FP detection (skeletonization)
        mc.eyeBrowBinMatArr[0] = binMat;

        //define tracking template for eyebrow
        mc.eyeBrowTrackingTemplateArr[i] = mc.grayFrame.submat(mc.eyeBrowBoundRectArr[i]);
    }

    //compute eyebrow interrocular distance
    mc.eyeBrowBaseDst = Math.abs(mc.eyeBrowBoundRectArr[0].x + mc.eyeBrowBoundRectArr[0].width / 2
            - (mc.eyeBrowBoundRectArr[1].x + mc.eyeBrowBoundRectArr[1].width / 2));

    LOG.info("eyeBrowBaseDst = " + mc.eyeBrowBaseDst);

    //define new bound rect centers for tracking template
    mc.eyeBrowCentersPointsArr = new Point[2];

    return true;
}