Example usage for org.opencv.core Mat zeros

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

Introduction

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

Prototype

public static Mat zeros(Size size, int type) 

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;//from   w w w  .j  av  a 2 s  .  co  m

    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:com.astrocytes.core.operationsengine.OperationsImpl.java

License:Open Source License

private List<Mat> showClusters(Mat cutout, Mat labels, Mat centers) {
    centers.convertTo(centers, CvType.CV_8UC1, 255.0);
    centers.reshape(3);/*from ww w .  ja va2s .c  o m*/

    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);
    }

    for (int y = 0; y < cutout.rows(); y++) {
        int rows = 0;
        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++;
        }
    }
    System.out.println(counts);
    return clusters;
}

From source file:com.wallerlab.compcellscope.MultiModeViewActivity.java

License:BSD License

public Mat onCameraFrame(CvCameraViewFrame inputFrame) {

    mCamera = mOpenCvCameraView.getCameraObject();
    mRgba = inputFrame.rgba();/*from w w w. j a v a 2  s.  c  o m*/

    Camera.Parameters camParams;
    camParams = mCamera.getParameters();

    int bfCompensation = 0;
    int dfCompensation = 0 * camParams.getMaxExposureCompensation();

    if (viewMode == 0) {
        switch (frameNum) {
        case 1: // Left
        {
            mRgba.copyTo(dpcLeft);
            sendData("dr");
            frameNum = 2;
            break;
        }
        case 2: // Right
        {
            mRgba.copyTo(dpcRight);
            sendData("dt");
            frameNum = 3;
            break;
        }
        case 3: // Top
        {
            mRgba.copyTo(dpcTop);
            sendData("db");
            frameNum = 4;
            break;
        }
        case 4: // Bottom
        {
            mRgba.copyTo(dpcBottom);
            sendData("bf");
            camParams.setExposureCompensation(bfCompensation);
            mCamera.setParameters(camParams);
            frameNum = 5;
            break;
        }
        case 5: // Brightfield
        {
            camParams.setExposureCompensation(dfCompensation);
            mCamera.setParameters(camParams);
            mRgba.copyTo(bfImg);
            sendData("an");

            frameNum = 6;
            break;
        }
        case 6: // Darkfield
        {
            mRgba.copyTo(dfImg);
            sendData("dl");

            frameNum = 1;
            break;
        }
        }
        //dpcLRImg = calcDPC(dpcLeft, dpcRight,dpcLRImg);
        new calcDPCTask().execute(dpcLeft, dpcRight, dpcLRImg);
        new calcDPCTask().execute(dpcTop, dpcBottom, dpcTBImg);
    } else {
        switch (viewMode) {
        case 1: {
            dpcSwitch = !dpcSwitch;
            if (dpcSwitch) {
                sendData("dl");
                mRgba.copyTo(dpcLeft);
            } else {
                sendData("dr");
                mRgba.copyTo(dpcRight);
            }
            new calcDPCTask().execute(dpcLeft, dpcRight, dpcLRImg);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //dpcLRImg = calcDPC(dpcLeft, dpcRight,dpcLRImg);
            break;
        }
        case 3: {
            dpcSwitch = !dpcSwitch;
            if (dpcSwitch) {
                sendData("db");
                mRgba.copyTo(dpcTop);
            } else {
                sendData("dt");
                mRgba.copyTo(dpcBottom);
            }
            new calcDPCTask().execute(dpcTop, dpcBottom, dpcTBImg);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //dpcTBImg = calcDPC(dpcTop, dpcBottom,dpcTBImg);
            break;
        }
        case 4: {

            sendData("bf");
            mRgba.copyTo(bfImg);
            //Log.d(TAG,"Displayed bf img");
            break;
        }
        case 5: {
            if (updateTrig) {
                sendData("an");
                updateTrig = false;
            }
            mRgba.copyTo(dfImg);
            //Log.d(TAG,"Displayed df img");
            break;
        }
        }
    }
    mmGrid = Mat.zeros(mmGrid.size(), mmGrid.type());
    if (viewMode == 0)
        mmGrid = generateMMFrame(mmGrid, bfImg, dfImg, dpcLRImg, dpcTBImg);
    else if (viewMode == 1)
        mmGrid = dpcLRImg;
    else if (viewMode == 3)
        mmGrid = dpcTBImg;
    else if (viewMode == 4)
        mmGrid = bfImg;
    else if (viewMode == 5)
        mmGrid = dfImg;

    return mmGrid;
}

From source file:cx.uni.jk.mms.iaip.mat.MatModel.java

License:Open Source License

public void clear(int width, int height) throws IllegalSizeException {
    if (width % 2 == 1 || height % 2 == 1) {
        throw new IllegalSizeException(
                "Images must have even width and even height in order to perform DCT/IDCT.");
    }/* www.  ja  v  a2s .c om*/

    this.mat = Mat.zeros(new Size(width, height), MAT_TYPE);
}

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
     *//* w  w w  .j  av  a  2  s  .co  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:net.bsrc.cbod.opencv.OpenCV.java

/**
 * Helper method//from ww w.j a v  a  2 s  .  c  o  m
 *
 * @param org
 * @param list
 * @return
 */
private static Mat getImageWithBlackBg(Mat org, List<Point> list) {

    Mat region = Mat.zeros(org.size(), org.type());

    for (Point p : list) {
        int row = (int) p.y;
        int col = (int) p.x;
        region.put(row, col, org.get(row, col));
    }

    return region;
}

From source file:opencv.CaptchaDetection.java

private static Mat thres_rgb(Mat src) {
    Mat gray = Mat.zeros(src.size(), CvType.CV_8UC1);

    //  , ?//from w  ww  .jav  a2 s .c om
    int thres = 150;
    double gamma = 2.5;

    for (int row = 0; row < src.rows(); row++) {
        for (int col = 0; col < src.cols(); col++) {
            double[] s_data = src.get(row, col);

            byte[] s_buff = new byte[3];
            byte[] g_buff = new byte[1];

            double color_sum = s_data[0] + s_data[1] + s_data[2];

            if (color_sum / 3 > thres) {
                for (int channel = 0; channel < 3; channel++)
                    s_buff[channel] = (byte) 255;

                g_buff[0] = 0;
            } else {
                //   gamma 
                for (int channel = 0; channel < 3; channel++) {
                    double tmp = s_data[channel];
                    tmp = Math.pow(tmp / 255, gamma) * 255;

                    if (tmp < 0)
                        s_buff[channel] = 0;
                    else if (tmp > 255)
                        s_buff[channel] = (byte) 255;
                    else
                        s_buff[channel] = (byte) tmp;
                }

                g_buff[0] = (byte) 255;
            }
            src.put(row, col, s_buff);
            gray.put(row, col, g_buff);
        }
    }
    return gray;
}

From source file:opencv.CaptchaDetection.java

private static Mat k_means_spilter(Mat src) {
    Mat dst = Mat.zeros(src.size(), CvType.CV_8UC1);

    int width = src.cols();
    int height = src.rows();
    int dims = src.channels();

    //   // w  ww  .  j a  v  a  2  s  .com
    int clusterCount = 3;

    Mat points = new Mat(width * height, dims, CvType.CV_32F, new Scalar(0));
    Mat centers = new Mat(clusterCount, dims, CvType.CV_32F);
    Mat labels = new Mat(width * height, 1, CvType.CV_32S);

    //    points
    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            int index = row * width + col;
            double[] s_data = src.get(row, col);

            for (int channel = 0; channel < 3; channel++) {
                float[] f_buff = new float[1];
                f_buff[0] = (float) s_data[channel];

                points.put(index, channel, f_buff);
            }
        }
    }

    //  knn ?
    TermCriteria criteria = new TermCriteria(TermCriteria.EPS + TermCriteria.MAX_ITER, 10, 0.1);
    Core.kmeans(points, clusterCount, labels, criteria, 3, Core.KMEANS_PP_CENTERS, centers);

    //  ??? label index
    Map<Integer, Integer> tmp = new TreeMap<>();
    for (int i = 0; i < clusterCount; i++) {
        int sum = 0;
        for (int j = 0; j < dims; j++) {
            sum += centers.get(i, j)[0];
        }
        while (tmp.containsKey(sum))
            sum++;
        tmp.put(sum, i);
    }

    int count = 0;
    int[] label_order = new int[clusterCount];
    for (Map.Entry<Integer, Integer> iter : tmp.entrySet()) {
        label_order[count++] = iter.getValue();
    }

    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            int index = row * width + col;
            int label = (int) labels.get(index, 0)[0];

            if (label == label_order[1]) {
                byte[] d_buff = new byte[1];
                d_buff[0] = (byte) 255;
                dst.put(row, col, d_buff);
            }
        }
    }

    return dst;
}

From source file:opencv.CaptchaDetection.java

private static Mat check_is_line(Mat src) {
    Mat dst = Mat.zeros(src.size(), CvType.CV_8UC1);

    int min_length = 3;

    //  ?//from w  w  w.j a va 2s . c om
    for (int row = 0; row < src.rows(); row++) {
        for (int col = 0; col < src.cols(); col++) {
            if (src.get(row, col)[0] == 0)
                continue;

            //  ??
            boolean left_black = false, right_black = false;

            if (col == 0 || src.get(row, col - 1)[0] == 0)
                left_black = true;

            if (col == src.cols() - 1 || src.get(row, col + 1)[0] == 0)
                right_black = true;

            if (!left_black || !right_black)
                continue;

            //   
            int length = col_length(src, row, col);
            if (length > min_length) {
                byte[] d_buff = new byte[1];
                d_buff[0] = (byte) 255;
                dst.put(row, col, d_buff);
            }

        }
    }

    //  ?
    for (int row = 0; row < src.rows(); row++) {
        for (int col = 0; col < src.cols(); col++) {
            if (src.get(row, col)[0] == 0)
                continue;

            //  ?
            boolean up_black = false, down_black = false;

            if (row == 0 || src.get(row - 1, col)[0] == 0)
                up_black = true;

            if (row == src.rows() - 1 || src.get(row + 1, col)[0] == 0)
                down_black = true;

            if (!up_black || !down_black)
                continue;

            //  
            int length = row_length(src, row, col);
            if (length > min_length) {
                byte[] d_buff = new byte[1];
                d_buff[0] = (byte) 255;
                dst.put(row, col, d_buff);
            }
        }
    }

    return dst;
}

From source file:org.pattern.detection.contour.ContourDetectionAlgorithm.java

@Override
public List<? extends Particle> detectAndAssign(ParticleImage image) {

    // take the copy of image that we dont modify the original
    Mat img = new Mat();
    image.getPixels().copyTo(img);/*from  w w  w. jav a 2  s  .  c om*/
    // blur the image to denoise
    //Imgproc.blur(imagePixels, imagePixels, new Size(3, 3));

    // thresholds the image
    Mat thresholded = new Mat();
    //        Imgproc.threshold(imagePixels, thresholded,
    //                THRESHOLD, MAX, Imgproc.THRESH_TOZERO_INV);

    // thresholding
    Imgproc.adaptiveThreshold(img, thresholded, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C,
            Imgproc.THRESH_BINARY_INV, 155, 15);
    Highgui.imwrite("1_thresholded.jpg", thresholded);

    Mat edges = new Mat();
    Imgproc.Canny(img, edges, 100, 200);
    Highgui.imwrite("1_canny.jpg", edges);

    // remove small noises
    //        Mat kernel = Mat.ones(new Size(3, 3), CvType.CV_8UC1);
    Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_CROSS, new Size(5, 5));

    Imgproc.morphologyEx(thresholded, thresholded, Imgproc.MORPH_OPEN, kernel);
    Highgui.imwrite("2_opening.jpg", thresholded);

    //        Imgproc.erode(thresholded, thresholded, kernel, ORIGIN, 3);
    //        Highgui.imwrite("3_erode.jpg", thresholded);

    Mat distTransform = new Mat();
    Imgproc.distanceTransform(thresholded, distTransform, Imgproc.CV_DIST_C, 5);
    distTransform.convertTo(distTransform, CvType.CV_8UC1);
    Imgproc.equalizeHist(distTransform, distTransform);
    Highgui.imwrite("4_distance_transform.jpg", distTransform);

    Mat markerMask = Mat.zeros(img.size(), CvType.CV_8UC1);
    double max = Core.minMaxLoc(distTransform).maxVal;
    Imgproc.threshold(distTransform, markerMask, max * 0.9, 255, Imgproc.THRESH_BINARY);
    markerMask.convertTo(markerMask, CvType.CV_8UC1);
    Highgui.imwrite("5_thresholded_distance.jpg", markerMask);

    List<MatOfPoint> contours = new ArrayList<>();
    Imgproc.findContours(markerMask, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE,
            ORIGIN);

    Mat markers = Mat.zeros(img.size(), CvType.CV_32S);
    //markers.setTo(Scalar.all(0));
    Random rand = new Random();
    for (int idx = 0; idx < contours.size(); idx++) {
        Scalar color = new Scalar(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255));
        Imgproc.drawContours(markers, contours, idx, color, -1);
    }
    Highgui.imwrite("6_markers.jpg", markers);

    Imgproc.cvtColor(img, img, Imgproc.COLOR_GRAY2RGB);
    img.convertTo(img, CvType.CV_8UC3);
    Imgproc.watershed(img, markers);
    Highgui.imwrite("7_wattershed.jpg", markers);

    // detect contours
    //        List<MatOfPoint> contours = new ArrayList<>();
    Imgproc.findContours(thresholded, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE,
            ORIGIN);

    // create particle from each contour
    List<Particle> particles = new ArrayList<>();
    int i = 0;
    for (MatOfPoint contour : contours) {
        Point cog = calcCog(contour);
        if (!Double.isNaN(cog.x) && !Double.isNaN(cog.y)) {
            System.out.println(cog);
            Particle p = new Particle(cog, contour);
            particles.add(p); // just for reorting reasons
            image.assign(p);
        }
    }

    return particles;
}