Example usage for org.opencv.core Mat cols

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

Introduction

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

Prototype

public int cols() 

Source Link

Usage

From source file:org.lasarobotics.vision.detection.objects.Detectable.java

License:Open Source License

/**
 * Gets the average color of the object//from   w  w  w.  j a va2 s . c  o  m
 *
 * @param img      The image matrix, of any color size
 * @param imgSpace The image's color space
 * @return The average color of the region
 */
public Color averageColor(Mat img, ColorSpace imgSpace) {
    //Coerce values to stay within screen dimensions
    double leftX = MathUtil.coerce(0, img.cols() - 1, left());
    double rightX = MathUtil.coerce(0, img.cols() - 1, right());

    double topY = MathUtil.coerce(0, img.rows() - 1, top());
    double bottomY = MathUtil.coerce(0, img.rows() - 1, bottom());

    //Input points into array for calculation
    //TODO rectangular submatrix-based calculation isn't perfectly accurate when you have ellipses or weird shapes
    Mat subMat = img.submat((int) topY, (int) bottomY, (int) leftX, (int) rightX);

    //Calculate average and return new color instance
    return Color.create(Core.mean(subMat), imgSpace);
}

From source file:org.lasarobotics.vision.util.color.Color.java

License:Open Source License

/**
 * Rapidly convert an RGBA matrix to a Grayscale matrix, bypassing
 * most of the color conversion overhead.
 *
 * @param rgba RGBA matrix// w  w  w  .j ava2 s .c om
 * @return Grayscale matrix
 */
public static Mat rapidConvertRGBAToGRAY(Mat rgba) {
    Mat gray = new Mat(rgba.rows(), rgba.cols(), CvType.CV_8UC1);
    Imgproc.cvtColor(rgba, gray, Imgproc.COLOR_RGBA2GRAY);
    return gray;
}

From source file:org.openpnp.machine.reference.vision.OpenCvVisionProvider.java

License:Open Source License

/**
 * Attempt to find matches of the given template within the current camera
 * frame. Matches are returned as TemplateMatch objects which contain
 * a Location in Camera coordinates. The results are sorted best score
 * to worst score.// w w  w. j  ava  2s .  c o  m
 * @param template
 * @return
 */
public List<TemplateMatch> getTemplateMatches(BufferedImage template) {
    // TODO: ROI
    BufferedImage image = camera.capture();

    // Convert the camera image and template image to the same type. This
    // is required by the cvMatchTemplate call.
    template = OpenCvUtils.convertBufferedImage(template, BufferedImage.TYPE_BYTE_GRAY);
    image = OpenCvUtils.convertBufferedImage(image, BufferedImage.TYPE_BYTE_GRAY);

    Mat templateMat = OpenCvUtils.toMat(template);
    Mat imageMat = OpenCvUtils.toMat(image);
    Mat resultMat = new Mat();

    Imgproc.matchTemplate(imageMat, templateMat, resultMat, Imgproc.TM_CCOEFF_NORMED);

    Mat debugMat = null;
    if (logger.isDebugEnabled()) {
        debugMat = imageMat.clone();
    }

    MinMaxLocResult mmr = Core.minMaxLoc(resultMat);
    double maxVal = mmr.maxVal;

    // TODO: Externalize?
    double threshold = 0.7f;
    double corr = 0.85f;

    double rangeMin = Math.max(threshold, corr * maxVal);
    double rangeMax = maxVal;

    List<TemplateMatch> matches = new ArrayList<TemplateMatch>();
    for (Point point : matMaxima(resultMat, rangeMin, rangeMax)) {
        TemplateMatch match = new TemplateMatch();
        int x = point.x;
        int y = point.y;
        match.score = resultMat.get(y, x)[0] / maxVal;

        if (logger.isDebugEnabled()) {
            Core.rectangle(debugMat, new org.opencv.core.Point(x, y),
                    new org.opencv.core.Point(x + templateMat.cols(), y + templateMat.rows()), new Scalar(255));
            Core.putText(debugMat, "" + match.score,
                    new org.opencv.core.Point(x + templateMat.cols(), y + templateMat.rows()),
                    Core.FONT_HERSHEY_PLAIN, 1.0, new Scalar(255));
        }

        Location offsets = getPixelCenterOffsets(x + (templateMat.cols() / 2), y + (templateMat.rows() / 2));
        match.location = camera.getLocation().subtract(offsets);
        matches.add(match);
    }

    Collections.sort(matches, new Comparator<TemplateMatch>() {
        @Override
        public int compare(TemplateMatch o1, TemplateMatch o2) {
            return ((Double) o2.score).compareTo(o1.score);
        }
    });

    saveDebugImage("template", templateMat);
    saveDebugImage("camera", imageMat);
    saveDebugImage("result", resultMat);
    saveDebugImage("debug", debugMat);

    return matches;
}

From source file:org.openpnp.machine.reference.vision.OpenCvVisionProvider.java

License:Open Source License

@Override
public Point[] locateTemplateMatches(int roiX, int roiY, int roiWidth, int roiHeight, int coiX, int coiY,
        BufferedImage templateImage_) throws Exception {
    BufferedImage cameraImage_ = camera.capture();

    // Convert the camera image and template image to the same type. This
    // is required by the cvMatchTemplate call.
    templateImage_ = OpenCvUtils.convertBufferedImage(templateImage_, BufferedImage.TYPE_INT_ARGB);
    cameraImage_ = OpenCvUtils.convertBufferedImage(cameraImage_, BufferedImage.TYPE_INT_ARGB);

    Mat templateImage = OpenCvUtils.toMat(templateImage_);
    Mat cameraImage = OpenCvUtils.toMat(cameraImage_);
    Mat roiImage = new Mat(cameraImage, new Rect(roiX, roiY, roiWidth, roiHeight));

    // http://stackoverflow.com/questions/17001083/opencv-template-matching-example-in-android
    Mat resultImage = new Mat(roiImage.cols() - templateImage.cols() + 1,
            roiImage.rows() - templateImage.rows() + 1, CvType.CV_32FC1);
    Imgproc.matchTemplate(roiImage, templateImage, resultImage, Imgproc.TM_CCOEFF);

    MinMaxLocResult mmr = Core.minMaxLoc(resultImage);

    org.opencv.core.Point matchLoc = mmr.maxLoc;
    double matchValue = mmr.maxVal;

    // TODO: Figure out certainty and how to filter on it.

    logger.debug(/*from w ww  . j a  va 2 s. c o  m*/
            String.format("locateTemplateMatches certainty %f at %f, %f", matchValue, matchLoc.x, matchLoc.y));
    locateTemplateMatchesDebug(roiImage, templateImage, matchLoc);

    return new Point[] { new Point(((int) matchLoc.x) + roiX, ((int) matchLoc.y) + roiY) };
}

From source file:org.openpnp.machine.reference.vision.OpenCvVisionProvider.java

License:Open Source License

private void locateTemplateMatchesDebug(Mat roiImage, Mat templateImage, org.opencv.core.Point matchLoc) {
    if (logger.isDebugEnabled()) {
        try {//from ww w .j  a  v  a2 s.c om
            Core.rectangle(roiImage, matchLoc, new org.opencv.core.Point(matchLoc.x + templateImage.cols(),
                    matchLoc.y + templateImage.rows()), new Scalar(0, 255, 0));

            BufferedImage debugImage = OpenCvUtils.toBufferedImage(roiImage);
            File file = Configuration.get().createResourceFile(OpenCvVisionProvider.class, "debug_", ".png");
            ImageIO.write(debugImage, "PNG", file);
            logger.debug("Debug image filename {}", file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.openpnp.machine.reference.vision.OpenCvVisionProvider.java

License:Open Source License

static List<Point> matMaxima(Mat mat, double rangeMin, double rangeMax) {
    List<Point> locations = new ArrayList<Point>();

    int rEnd = mat.rows() - 1;
    int cEnd = mat.cols() - 1;

    // CHECK EACH ROW MAXIMA FOR LOCAL 2D MAXIMA
    for (int r = 0; r <= rEnd; r++) {
        MinMaxState state = MinMaxState.BEFORE_INFLECTION;
        double curVal = mat.get(r, 0)[0];
        for (int c = 1; c <= cEnd; c++) {
            double val = mat.get(r, c)[0];

            if (val == curVal) {
                continue;
            } else if (curVal < val) {
                if (state == MinMaxState.BEFORE_INFLECTION) {
                    // n/a
                } else {
                    state = MinMaxState.BEFORE_INFLECTION;
                }//from  www.  j  a  v  a  2 s .c om
            } else { // curVal > val
                if (state == MinMaxState.BEFORE_INFLECTION) {
                    if (rangeMin <= curVal && curVal <= rangeMax) { // ROW
                                                                    // MAXIMA
                        if (0 < r && (mat.get(r - 1, c - 1)[0] >= curVal || mat.get(r - 1, c)[0] >= curVal)) {
                            // cout << "reject:r-1 " << r << "," << c-1 <<
                            // endl;
                            // - x x
                            // - - -
                            // - - -
                        } else if (r < rEnd
                                && (mat.get(r + 1, c - 1)[0] > curVal || mat.get(r + 1, c)[0] > curVal)) {
                            // cout << "reject:r+1 " << r << "," << c-1 <<
                            // endl;
                            // - - -
                            // - - -
                            // - x x
                        } else if (1 < c
                                && (0 < r && mat.get(r - 1, c - 2)[0] >= curVal || mat.get(r, c - 2)[0] > curVal
                                        || r < rEnd && mat.get(r + 1, c - 2)[0] > curVal)) {
                            // cout << "reject:c-2 " << r << "," << c-1 <<
                            // endl;
                            // x - -
                            // x - -
                            // x - -
                        } else {
                            locations.add(new Point(c - 1, r));
                        }
                    }
                    state = MinMaxState.AFTER_INFLECTION;
                } else {
                    // n/a
                }
            }

            curVal = val;
        }

        // PROCESS END OF ROW
        if (state == MinMaxState.BEFORE_INFLECTION) {
            if (rangeMin <= curVal && curVal <= rangeMax) { // ROW MAXIMA
                if (0 < r && (mat.get(r - 1, cEnd - 1)[0] >= curVal || mat.get(r - 1, cEnd)[0] >= curVal)) {
                    // cout << "rejectEnd:r-1 " << r << "," << cEnd-1 <<
                    // endl;
                    // - x x
                    // - - -
                    // - - -
                } else if (r < rEnd
                        && (mat.get(r + 1, cEnd - 1)[0] > curVal || mat.get(r + 1, cEnd)[0] > curVal)) {
                    // cout << "rejectEnd:r+1 " << r << "," << cEnd-1 <<
                    // endl;
                    // - - -
                    // - - -
                    // - x x
                } else if (1 < r && mat.get(r - 1, cEnd - 2)[0] >= curVal || mat.get(r, cEnd - 2)[0] > curVal
                        || r < rEnd && mat.get(r + 1, cEnd - 2)[0] > curVal) {
                    // cout << "rejectEnd:cEnd-2 " << r << "," << cEnd-1 <<
                    // endl;
                    // x - -
                    // x - -
                    // x - -
                } else {
                    locations.add(new Point(cEnd, r));
                }
            }
        }
    }

    return locations;
}

From source file:org.openpnp.vision.FluentCv.java

License:Open Source License

/**
 * Draw the infinite line defined by the two points to the extents of the image instead of just
 * between the two points. From://from   w w w .  java2 s .  com
 * http://stackoverflow.com/questions/13160722/how-to-draw-line-not-line-segment-opencv-2-4-2
 * 
 * @param img
 * @param p1
 * @param p2
 * @param color
 */
public static void infiniteLine(Mat img, Point p1, Point p2, Color color) {
    Point p = new Point(), q = new Point();
    // Check if the line is a vertical line because vertical lines don't
    // have slope
    if (p1.x != p2.x) {
        p.x = 0;
        q.x = img.cols();
        // Slope equation (y1 - y2) / (x1 - x2)
        float m = (float) ((p1.y - p2.y) / (p1.x - p2.x));
        // Line equation: y = mx + b
        float b = (float) (p1.y - (m * p1.x));
        p.y = m * p.x + b;
        q.y = m * q.x + b;
    } else {
        p.x = q.x = p2.x;
        p.y = 0;
        q.y = img.rows();
    }
    Core.line(img, p, q, colorToScalar(color));
}

From source file:org.openpnp.vision.FluentCv.java

License:Open Source License

/**
 * From FireSight: https://github.com/firepick1/FireSight/wiki/op-Sharpness
 * //ww  w.  ja va  2 s  . c  o m
 * @param image
 * @return
 */
public static double calculateSharpnessGRAS(Mat image) {
    int sum = 0;
    Mat matGray = new Mat();

    if (image.channels() == 1) {
        matGray = image;
    } else {
        Imgproc.cvtColor(image, matGray, Imgproc.COLOR_BGR2GRAY);
    }

    byte[] b1 = new byte[1];
    byte[] b2 = new byte[1];
    for (int r = 0; r < matGray.rows(); r++) {
        for (int c = 0; c < matGray.cols() - 1; c++) {
            matGray.get(r, c, b1);
            matGray.get(r, c + 1, b2);
            int df = (int) b1[0] - (int) b2[0];
            sum += df * df;
        }
    }

    return ((double) sum / matGray.rows() / (matGray.cols() - 1));
}

From source file:org.pattern.utils.MatUtils.java

/**
 * Compares if two image matrices contains similar data.
 * //from ww  w . j  a  v  a 2  s  .c  om
 * @param mat1
 * @param mat2
 * @return 
 */
public static boolean similar(Mat mat1, Mat mat2) {

    if (mat1.cols() != mat2.cols() || mat1.rows() != mat2.rows()) {
        return false;
    }

    Mat mat = new Mat();
    Core.compare(mat1, mat2, mat, Core.CMP_EQ);
    return Core.countNonZero(mat) != 0;
}

From source file:org.sikuli.script.Finder.java

License:MIT License

private static void printMatI(Mat mat) {
    int[] data = new int[mat.channels()];
    for (int r = 0; r < mat.rows(); r++) {
        for (int c = 0; c < mat.cols(); c++) {
            mat.get(r, c, data);/*ww w.j av a2 s  . c  o m*/
            log(lvl, "(%d, %d) %s", r, c, Arrays.toString(data));
        }
    }
}