Example usage for org.opencv.core Mat Mat

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

Introduction

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

Prototype

public Mat() 

Source Link

Usage

From source file:imageanalysis.Analyzer.java

private Mat findDifferences() {
    Mat image = ImgTools.getImageFromClipboard();

    // Gets images (both halves)
    Mat leftHalf = image.submat(left);// w  w w  . jav a  2  s. com
    Mat rightHalf = image.submat(right);

    // Computes their difference
    Mat diff1 = new Mat();
    Mat diff2 = new Mat();
    Core.subtract(leftHalf, rightHalf, diff1);
    Core.subtract(rightHalf, leftHalf, diff2);

    // Gets sum of both differences (image that highlightes different objects)
    Mat sum = new Mat(diff1.size(), CvType.CV_32F);
    Core.add(diff1, diff2, sum);
    // Normalize
    Core.normalize(sum, sum, 0, 255, Core.NORM_MINMAX);
    sum.convertTo(sum, CvType.CV_8U);

    return sum;

}

From source file:imageanalysis.Analyzer.java

public boolean compareRoiAgainstPattern(int xcoord, int ycoord, int width, int height) {
    screen = ImgTools.getImageFromClipboard();

    // Crops roi around chosen mouse point
    Rect roi = new Rect(xcoord - width / 2, ycoord - height / 2, width, height);
    Mat actionButton = screen.submat(roi);

    // Preprocessing
    Imgproc.cvtColor(actionButton, actionButton, Imgproc.COLOR_BGR2GRAY);
    //        Imgproc.medianBlur(actionButton, actionButton, 5);

    // Referent pattern
    Mat bonefoodPattern = Patterns.getBonefoodPattern();
    //        Imgproc.medianBlur(bonefoodPattern, bonefoodPattern, 5);

    // Match template
    // ... result should be the refPoint
    Mat result = new Mat();
    Imgproc.matchTemplate(actionButton, bonefoodPattern, result, Imgproc.TM_SQDIFF);
    Point p = Core.minMaxLoc(result).minLoc;
    //        System.out.println(p.toString());

    return p.equals(refPoint);
}

From source file:imageanalysis.Analyzer.java

public Point checkForX() {
    screen = ImgTools.getImageFromClipboard();

    Mat image = screen.clone();//from   w  w  w  . j  a  va 2  s  .c  o m

    // Preprocessing
    Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2GRAY);

    // Referent pattern
    Mat xPattern = Patterns.getXbuttPattern();

    // Match template
    // ... result should be the refPoint
    Mat result = new Mat();
    Imgproc.matchTemplate(image, xPattern, result, Imgproc.TM_SQDIFF);

    Core.MinMaxLocResult mm = Core.minMaxLoc(result);

    Point p = mm.minLoc;
    double val = mm.minVal;

    if (val < 1000000) {
        p.x += 10;
        p.y += 10;
        return p;
    } else {
        return null;
    }
}

From source file:imageanalyzercv.ImageAnalyzerCV.java

/**
 * @param args the command line arguments
 *//*from   www  . j  a va 2s  .com*/
public static void main(String[] args) {
    System.out.println("path: " + System.getProperty("java.library.path"));
    System.loadLibrary("opencv_java300");

    Mat m = Highgui.imread("/Users/chintan/Downloads/software/image_analyis/mydata/SAM_0763.JPG");
    System.out.println("m = " + m.height());
    MatOfKeyPoint points = new MatOfKeyPoint();
    FeatureDetector.create(FeatureDetector.SURF).detect(m, points);

    Mat m2 = Highgui.imread("/Users/chintan/Downloads/software/image_analyis/mydata/SAM_0764.JPG");
    System.out.println("m = " + m2.height());
    MatOfKeyPoint points2 = new MatOfKeyPoint();
    FeatureDetector.create(FeatureDetector.SURF).detect(m2, points2);

    DescriptorExtractor SurfExtractor = DescriptorExtractor.create(DescriptorExtractor.BRISK);
    Mat imag1Desc = new Mat();
    SurfExtractor.compute(m, points, imag1Desc);

    Mat imag2Desc = new Mat();
    SurfExtractor.compute(m2, points2, imag2Desc);

    MatOfDMatch matches = new MatOfDMatch();

    Mat imgd = new Mat();
    imag1Desc.copyTo(imgd);
    System.out.println(imgd.size());
    DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING).match(imag2Desc, imag1Desc,
            (MatOfDMatch) matches);

    double min_distance = 1000.0;
    double max_distance = 0.0;
    DMatch[] matchArr = matches.toArray();
    for (int i = 0; i < matchArr.length; i++) {
        if (matchArr[i].distance > max_distance)
            max_distance = matchArr[i].distance;
        if (matchArr[i].distance < min_distance)
            min_distance = matchArr[i].distance;
    }

    ArrayList<DMatch> good_matches = new ArrayList<DMatch>();

    System.out.println("Min Distance: " + min_distance + "  Max distance: " + max_distance);
    double totalScore = 0.0;
    for (int j = 0; j < imag1Desc.rows() && j < matchArr.length; j++) {
        if ((matchArr[j].distance <= (11 * min_distance)) && (matchArr[j].distance >= min_distance * 1)) {
            good_matches.add(matchArr[j]);
            //System.out.println(matchArr[j]);
            totalScore = totalScore + matchArr[j].distance;

        }
        //good_matches.add(matchArr[j]);

    }
    System.out.println((1 - (totalScore / (good_matches.size() * ((max_distance + min_distance) / 2)))) * 100);
    // System.out.println(matches.toList().size());
    Mat out = new Mat();
    MatOfDMatch mats = new MatOfDMatch();
    mats.fromList(good_matches);
    Features2d.drawMatches(m2, points2, m, points, mats, out);
    Highgui.imwrite("/Users/chintan/Downloads/one2.jpg", out);
}

From source file:imagegame.Camera.java

public Camera() {
    super("Camera - click screen to take a picture");
    initComponents();//from  ww w.  ja  va  2s. co m

    setLayout(new BorderLayout());
    setLibraryPath();
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    videoCapture = new VideoCapture();
    videoCapture.open(0);

    System.out.println("Camera open: " + videoCapture.isOpened());
    if (videoCapture.isOpened()) {
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                // Implementation here

                stop();
                System.out.println("Camera released");

            }
        });//end WindowListener
        JPanel cameraJPanel = new JPanel() {
            @Override
            public void paint(Graphics g) {
                g.drawImage(image, 0, 0, this);
            }
        };
        cameraJPanel.setPreferredSize(new Dimension(420, 500));
        add(cameraJPanel, BorderLayout.NORTH);

        Runnable frameGrabber;
        frameGrabber = () -> {
            Mat mat = new Mat();
            videoCapture.read(mat);

            image = mat2BufferedImage(mat);
            //g.drawImage(image, 0, 0,this);
            cameraJPanel.repaint();
            //              rectList.stream().forEach((Rectangle2D rect) -> {
            //                g2d.strokeRect(rect.getMinX(), rect.getMinY(), rect.getWidth(), rect.getHeight());
            //            });
        }; //end frameGrabber
        this.timer = Executors.newSingleThreadScheduledExecutor();
        this.timer.scheduleAtFixedRate(frameGrabber, 0, 133, TimeUnit.MILLISECONDS);
    } else {//if videoCapture.isOpen() is false
        JOptionPane.showMessageDialog(null, "You have no camera installed");
    }
}

From source file:imageprocess.HistogramProcessor.java

public static Mat getGrayHistogram(Mat image) {

    Mat grayHist = new Mat();

    // Compute histogram
    Imgproc.calcHist(Arrays.asList(image), //histogram of 1 image only
            new MatOfInt(0), // the channel used
            new Mat(), // no mask is used
            grayHist, // the resulting histogram
            new MatOfInt(256), // number of bins, hist size
            new MatOfFloat(0.0f, 255.0f) // BRG range
    );//ww w  . j  a v a  2 s  . c  om

    return grayHist;
}

From source file:imageprocess.HistogramProcessor.java

public static Mat getHistogram(Mat image) {

    Mat hist = new Mat();

    // Compute histogram
    Imgproc.calcHist(Arrays.asList(image), //histogram of 1 image only
            new MatOfInt(0, 1, 2), // the channel used
            new Mat(), // no mask is used
            hist, // the resulting histogram
            new MatOfInt(256, 256, 256), // number of bins, hist size
            new MatOfFloat(0.0f, 255.0f, 0.0f, 255.0f, 0.0f, 255.0f) // BRG range
    );/*from   www  .  jav  a  2s.  c  o m*/

    return hist;
}

From source file:imageprocess.HistogramProcessor.java

public static Mat getHueHistogram(Mat image) {

    Mat hue = new Mat();

    // Compute histogram
    Imgproc.calcHist(Arrays.asList(image), //histogram of 1 image only
            new MatOfInt(0, 1, 2), // the channel used
            new Mat(), // no mask is used
            hue, // the resulting histogram
            new MatOfInt(256, 256, 256), // number of bins, hist size
            new MatOfFloat(0.0f, 255.0f, 0.0f, 255.0f, 0.0f, 255.0f) // BRG range
    );/*from  w ww .  j a v  a 2 s.c o  m*/

    return hue;
}

From source file:imageprocess.ObjectFinder.java

public Mat getHueHistogram(final Mat image, int minSaturation) {

    Mat hist = new Mat();

    // Convert to Lab color space
    Mat hsv = new Mat();
    Imgproc.cvtColor(image, hsv, CV_BGR2HSV);
    Mat mask = new Mat();
    if (minSaturation > 0) {
        // Spliting the 3 channels into 3 images
        List<Mat> v = new ArrayList<>();
        Core.split(hsv, v);//from w ww . ja v  a 2 s  . c  o m
        // Mask out the low saturated pixels
        Imgproc.threshold(v.get(1), mask, minSaturation, 255, THRESH_BINARY);
    }
    // Compute histogram
    Imgproc.calcHist(Arrays.asList(image), new MatOfInt(0), // the hue channel used
            mask, // no mask is used
            hist, // the resulting histogram
            new MatOfInt(256), // number of bins
            new MatOfFloat(0.0f, 180.0f) // pixel value range
    );

    return hist;
}

From source file:imageprocess.ObjectFinder.java

public Mat find(final Mat image, MatOfInt channels, MatOfFloat ranges) {

    Mat result = new Mat();

    if (isIsSparse()) { // call the right function based on histogram type

        Imgproc.calcBackProject(Arrays.asList(image), channels, // vector specifying what histogram dimensions belong to what image channels
                ROIHistogram, // the histogram we are using
                result, // the resulting back projection image
                ranges, // the range of values, for each dimension
                255.0 // the scaling factor is chosen such that a histogram value of 1 maps to 255
        );//w  w  w .ja v  a 2s.  c  om

    } else {
        Imgproc.calcBackProject(Arrays.asList(image), channels, // vector specifying what histogram dimensions belong to what image channels
                ROIHistogram, // the histogram we are using
                result, // the resulting back projection image
                ranges, // the range of values, for each dimension
                255.0 // the scaling factor is chosen such that a histogram value of 1 maps to 255
        );
    }

    // Threshold back projection to obtain a binary image
    Mat thresholded = new Mat(result.rows(), result.cols(), result.type());
    if (getThreshold() > 0.0) {
        Imgproc.threshold(result, thresholded, 255 * getThreshold(), 255, THRESH_BINARY);
    }

    return thresholded;
}