Example usage for org.opencv.core Mat clone

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

Introduction

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

Prototype

public Mat clone() 

Source Link

Usage

From source file:edu.sust.cse.analysis.news.NewsAnalysis.java

public static void main(String[] args) throws IOException {

    //                Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\e-01.jpg");
    //                Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\e-01-145.jpg");
    //                Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\e-02.jpg");
    //                Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\e-03.jpg");
    //                Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\e-04.jpg");
    //                Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\e-05.jpg");
    //                 Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\sc-01.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\sc-04_resized.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\Camscanner Output\\normal_output_scan0007.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\Camscanner Output\\normal_output_scan0007-01.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\Camscanner Output\\normal_output_scan0001-01.bmp");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\scan-01-dec\\scan0007-300.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\scan-01-dec\\scan0007-145.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\scan-01-dec\\scan0007-145.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\scan-01-dec\\scan0007-96.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Google\\Thesis Work\\scan-01-dec\\scan0001-145.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Thesis-4-1\\Previous Work\\OPenCv2\\eProthomAlo Sample I-O\\e-5-12.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\Thesis-4-1\\Previous Work\\OPenCv2\\eProthomAlo Sample I-O\\e-6-12.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\06-12-2015\\sc-03-145.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\06-12-2015\\sc-03-145.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\06-12-2015\\sc-03-300B.jpg");
    Mat inputImageMat = Highgui/*ww w . j  a  v  a  2  s  .com*/
            .imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\06-12-2015\\sc-03-145B.jpg");
    if (null == inputImageMat) {
        System.out.println("[INPUT IMAGE NULL]");
    }
    Mat image = new Mat();//normal_output_scan0002.jpg
    double ratio = 150 / 72.0; // 4.167
    System.out.println("WIDTH: " + inputImageMat.width() + " HEIGHT:" + inputImageMat.height());
    int inputWidth = (int) (inputImageMat.width() * ratio);
    int inputHeight = (int) (inputImageMat.height() * ratio);
    System.out.println("WIDTH: " + inputWidth + " HEIGHT:" + inputHeight);

    //        inputImageMat = image;
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\sc-02.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\sc-03.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\sc-04.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\data1\\sc-05.jpg");
    //        Mat inputImageMat = Highgui.imread("D:\\OpenCV_Library\\resources\\Scan_Img\\image\\web001.png");
    Debug.debugLog("[Image [Cols, Rows]: [" + inputImageMat.cols() + ", " + inputImageMat.rows() + "]]");
    //        imshow("Original", inputImageMat);
    ViewerUI.show("Original", inputImageMat, ViewableUI.SHOW_ORIGINAL);
    //        ViewerUI.show("Original-Histogram", Histogram.getHistogram(inputImageMat), ViewableUI.SHOW_HISTOGRAM_ORIGINAL);

    // Do some image processing on the image and display in another window.
    Mat filteredImage = new Mat();
    /**
     * We have explained some filters which main goal is to smooth an input
     * image. However, sometimes the filters do not only dissolve the noise,
     * but also smooth away the edges
     */
    //        Imgproc.bilateralFilter(inputImageMat, m2, -1, 50, 10); /*Previous line for noise filtering*/
    Imgproc.bilateralFilter(inputImageMat, filteredImage, -1, 50, 10);
    //        Imgproc.bilateralFilter(inputImageMat, filteredImage, -1, 150, 11);

    ViewerUI.show("Noise Filter", filteredImage, ViewableUI.SHOW_NOISE_FILTER);
    //        ViewerUI.show("Noise Filter-Histogram", Histogram.getHistogram(filteredImage), ViewableUI.SHOW_HISTOGRAM_NOISE_FILTER);
    Imgproc.Canny(filteredImage, filteredImage, 10, 150);
    //        Imgproc.bilateralFilter(filteredImage, filteredImage, -1, 50, 10);
    //        Imgproc.threshold(filteredImage, filteredImage, 250, 300,Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C );
    //Imgproc.cvtColor(m1, m1, Imgproc.COLOR_RGB2GRAY, 0);
    //        imshow("Edge Detected", m2);
    ViewerUI.show("Edge Detected", filteredImage, ViewableUI.SHOW_EDGE_DETECTION);
    //        ViewerUI.show("Edge Detected-Histogram", Histogram.getHistogram(filteredImage), ViewableUI.SHOW_HISTOGRAM_EDGE_DETECTION);

    Size sizeA = filteredImage.size();
    System.out.println("Width: " + sizeA.width + " Height: " + sizeA.height);
    int width = (int) sizeA.width;
    int height = (int) sizeA.height;
    int pointLength[][][] = new int[height][width][2];
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            //double[] data = m2.get(i, j);
            if (filteredImage.get(i, j)[0] != 0) {
                pointLength[i][j][0] = 0;
                pointLength[i][j][1] = 0;
                continue;
            }
            if (j != 0 && filteredImage.get(i, j - 1)[0] == 0) {
                pointLength[i][j][0] = pointLength[i][j - 1][0];
            } else {
                int count = 0;
                for (int k = j + 1; k < width; k++) {
                    if (filteredImage.get(i, k)[0] == 0) {
                        count++;
                    } else {
                        break;
                    }
                }
                pointLength[i][j][0] = count;
            }
            if (i != 0 && filteredImage.get(i - 1, j)[0] == 0) {
                pointLength[i][j][1] = pointLength[i - 1][j][1];
            } else {
                int count = 0;
                for (int k = i + 1; k < height; k++) {
                    if (filteredImage.get(k, j)[0] == 0) {
                        count++;
                    } else {
                        break;
                    }
                }
                pointLength[i][j][1] = count;
            }
        }
    }
    String temp = "";
    Mat convertArea = filteredImage.clone();

    int[][] blackWhite = new int[height][width];

    for (int i = 0; i < height; i++) {
        temp = "";
        for (int j = 0; j < width; j++) {
            if (i == 0 || j == 0 || i == height - 1 || j == width - 1) {
                temp = temp + "@";
                blackWhite[i][j] = 1;

                double[] data = filteredImage.get(i, j);
                data[0] = 255.0;
                convertArea.put(i, j, data);
            } else if (pointLength[i][j][0] > 150 && pointLength[i][j][1] > 6) {
                temp = temp + "@";
                blackWhite[i][j] = 1;

                double[] data = filteredImage.get(i, j);
                data[0] = 255.0;
                convertArea.put(i, j, data);
            } else if (pointLength[i][j][0] > 7 && pointLength[i][j][1] > 200) {
                temp = temp + "@";
                blackWhite[i][j] = 1;

                double[] data = filteredImage.get(i, j);
                data[0] = 255.0;
                convertArea.put(i, j, data);
            } else {
                temp = temp + " ";
                blackWhite[i][j] = 0;

                double[] data = filteredImage.get(i, j);
                data[0] = 0.0;
                convertArea.put(i, j, data);
            }

        }
    }
    ViewerUI.show("Convertion", convertArea, ViewableUI.SHOW_CONVERSION);
    //        ViewerUI.show("Convertion-Histogram", Histogram.getHistogram(convertArea), ViewableUI.SHOW_HISTOGRAM_CONVERSION);

    ImageDetection isImage = new ImageDetection();
    HeadlineDetection isHeadline = new HeadlineDetection();

    ImageBorderDetectionBFS imgBFS = new ImageBorderDetectionBFS();
    ArrayList<BorderItem> borderItems = imgBFS.getBorder(blackWhite, width, height, filteredImage,
            inputImageMat);
    // Mat[] subMat = new Mat[borderItems.size()];
    //        for (int i = 0; i < borderItems.size(); i++) {
    //            subMat[i] = m2.submat(borderItems.get(i).getMinX(), borderItems.get(i).getMaxX(),
    //                    borderItems.get(i).getMinY(), borderItems.get(i).getMaxY());
    //            if (isImage.isImage(subMat[i])) {
    //                System.out.println("subMat" + i + " is an image");
    //                imshow("Image" + i, subMat[i]);
    //
    //            }else if(isHeadline.isHeadLine(subMat[i])){
    //                System.out.println("subMat" + i + " is an Headline");
    //                imshow("Headline" + i, subMat[i]);
    //            }else{
    //                System.out.println("subMat" + i + " is an Column");
    //                imshow("Column" + i, subMat[i]);
    //            }
    //            //imshow("subMat" + i, subMat[i]);
    //            bw.close();
    //
    //        }

    boolean[] imageIndexer = new boolean[borderItems.size()];
    int[] lineHeight = new int[borderItems.size()];
    int highestLinheight = -1, lowestLineHeight = 10000;
    int totalHeight = 0, notImage = 0;

    for (int i = 0; i < borderItems.size(); i++) {
        lineHeight[i] = 0;
        BorderItem borderItem = borderItems.get(i);
        //            subMat[i] = m2.submat(borderItems.get(i).getMinX(), borderItems.get(i).getMaxX(),
        //                    borderItems.get(i).getMinY(), borderItems.get(i).getMaxY());
        //            if (isImage.isImage(subMat[i])) {
        //                System.out.println("subMat" + i + " is an image");
        //                imshow("Image" + i, subMat[i]);
        //                imageIndexer[i] = true;
        //                continue;
        //            }else{
        //                notImage++;
        //                imageIndexer[i] = false;
        //            }
        if (borderItem.getIsImage()) {
            System.out.println("subMat" + i + " is an image");
            //                imshow("Image" + i, borderItem.getBlock());
            ViewerUI.show("Image" + i, borderItem.getBlock(), ViewableUI.SHOW_IMAGE);
            //                ViewerUI.show("Image-Histogram" + i, Histogram.getHistogram(borderItem.getBlock()), ViewableUI.SHOW_HISTOGRAM_IMAGE);

            imageIndexer[i] = true;
            continue;
        } else {
            notImage++;
            imageIndexer[i] = false;
        }

        //            totalHeight += lineHeight[i] = getLineHeight(subMat[i]);
        Mat fake = new Mat();
        Imgproc.cvtColor(borderItem.getBlock(), fake, Imgproc.COLOR_RGB2GRAY, 0);
        totalHeight += lineHeight[i] = getLineHeight(fake);
        fake.release();
        System.out.println("line height " + i + ": " + lineHeight[i]);
        //            imshow("" + i, borderItems.get(i).getBlock());
        if (lineHeight[i] > highestLinheight) {
            highestLinheight = lineHeight[i];
        }
        if (lineHeight[i] < lowestLineHeight) {
            lowestLineHeight = lineHeight[i];
        }

        //            if(i==7)
        //                break;
    }

    int avgLineHeight = totalHeight / notImage;

    for (int i = 0; i < borderItems.size(); i++) {
        if (!imageIndexer[i]) {
            if (lineHeight[i] - lowestLineHeight > 13 && lineHeight[i] >= 45) {
                //                    imshow("Headline" + i, subMat[i]);
                //                    imshow("Headline" + i, borderItems.get(i).getBlock());
                ViewerUI.show("Headline" + i, borderItems.get(i).getBlock(), ViewableUI.SHOW_HEADING);
                //                    ViewerUI.show("Headline-Histogram" + i, Histogram.getHistogram(borderItems.get(i).getBlock()), ViewableUI.SHOW_HISTOGRAM_HEADING);

            } else if (lineHeight[i] - lowestLineHeight > 8 && lineHeight[i] >= 21 && lineHeight[i] < 45) {
                //                    imshow("Sub Headline" + i, borderItems.get(i).getBlock());
                ViewerUI.show("Sub Headline" + i, borderItems.get(i).getBlock(), ViewableUI.SHOW_SUB_HEADING);
                //                    ViewerUI.show("Sub Headline-Histogram" + i, Histogram.getHistogram(borderItems.get(i).getBlock()), ViewableUI.SHOW_HISTOGRAM_SUB_HEADING);

            } else {
                //                    imshow("Column" + i, subMat[i]);
                //                    imshow("Column" + i, borderItems.get(i).getBlock());
                ViewerUI.show("Column" + i, borderItems.get(i).getBlock(), ViewableUI.SHOW_COLUMN);
                //                    ViewerUI.show("Column-Histogram" + i, Histogram.getHistogram(borderItems.get(i).getBlock()), ViewableUI.SHOW_HISTOGRAM_COLUMN);

            }
        }
    }

}

From source file:edu.sust.cse.detection.algorithm.ImageBorderDetectionBFS.java

public ArrayList<BorderItem> getBorder(int[][] image, int width, int height, Mat m2, Mat m1) {
    int result = 0;
    ImageBorderDetectionBFS.width = width;
    ImageBorderDetectionBFS.height = height;
    ImageBorderDetectionBFS.d = image;/*from   w w  w . jav a2  s .  c om*/
    ImageBorderDetectionBFS.m2 = m2.clone();
    ImageBorderDetectionBFS.m1 = m1.clone();
    //ReadFile();
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            minX = 1000000;
            maxX = -1;
            minY = 1000000;
            maxY = -1;
            if (d[i][j] == 0 && image[i][j] == 0) {
                result++;
                countAt = 1;
                bfs(image, i, j);

                if (countAt > 1500) {
                    canMaxiMizeBorder(minX, maxX, minY, maxY, width, height);
                    BorderItem item = new BorderItem(countAt, minX, maxX, minY, maxY, maxX - minX + 1,
                            maxY - minY + 1);
                    categorize(item, m2);
                }
            }
        }
    }

    //        int i = 0;
    //        System.out.println("SIze: "+otherItems.size());
    //removeImagesFromNonImageBlock();
    eraseImges();

    return borderItems;

}

From source file:edu.ucue.tfc.Modelo.VideoProcessor.java

public void processVideo() {
    do {// w  ww.ja  v  a 2 s.  c o m
        Mat tmp = new Mat();
        video.read(tmp);
        if (!tmp.empty()) {
            frame = tmp.clone();
            tmp.release();
            if (frameCounter < (getFrameCount() / 2) - 1) {
                frameCounter++;
                if (getMinutes() > 0) {
                    carsPerMinute = getDetectedCarsCount() / getMinutes();
                }

                processFrame(getFrame());
            } else {
                frameCounter = 0;
                finished = true;

                System.out.println("Reiniciando..");
                setFramePos(1);
            }
        } else {
            System.out.println("Imagen Vaca");
            frameCounter = 0;
            finished = true;

            System.out.println("Reiniciando..");
            setFramePos(1);
        }
    } while (frameCounter > (getFrameCount() / 2) - 2);
}

From source file:emotion.Eyebrow.java

public Eyebrow(EyeRegion eyeReg, boolean rightEyeFlag) {
    this.reg = eyeReg;
    Mat eye = rightEyeFlag ? Eye.rightEye.clone() : Eye.leftEye.clone();

    Mat eyebrowROI = eye.clone();
    //cvtColor(eyebrowROI, eyebrowROI, Imgproc.COLOR_BGR2GRAY);

    eyebrowROI.convertTo(eyebrowROI, CvType.CV_32F);
    //        Vector<Mat> channels=new Vector<>();  
    //        split(eyebrowROI,channels);
    //        imwrite("eyebrowROI.png", channels.get(0));

    Mat result = StaticFunctions.gabor(eyebrowROI);
    //threshold(result, result, 200,255, Imgproc.THRESH_BINARY_INV);

    imwrite("intermidiate.png", result);
    Harris(result, rightEyeFlag);/*from  w  w  w . j  a  v a2  s  .  c  o m*/
    imwrite("eyeafterGabor.png", result);
}

From source file:emotion.Eyebrow.java

public static void Harris(Mat img, boolean rightEyeFlag) {
    //Harris point extraction
    Mat harrisTestimg;// w w  w .jav a2  s .  c om
    harrisTestimg = img.clone();
    cvtColor(harrisTestimg, harrisTestimg, Imgproc.COLOR_BGR2GRAY);
    threshold(harrisTestimg, harrisTestimg, 200, 255, Imgproc.THRESH_BINARY_INV);
    Mat struct = Imgproc.getStructuringElement(Imgproc.MORPH_CROSS, new Size(3, 3));
    erode(harrisTestimg, harrisTestimg, struct);
    dilate(harrisTestimg, harrisTestimg, struct);
    imwrite("intermediateHaaris.jpg", harrisTestimg);
    harrisTestimg.convertTo(harrisTestimg, CV_8UC1);
    ArrayList<MatOfPoint> contours = new ArrayList<>();
    Mat hierarchy = new Mat();

    Imgproc.findContours(harrisTestimg, contours, hierarchy, Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_NONE);

    //System.out.println("Average Y for contours:");
    float[] averageY = new float[contours.size()];
    for (int i = 0; i < contours.size(); ++i) {
        //We calculate mean of Y coordinates for each contour
        for (int j = 0; j < contours.get(i).total(); ++j) {
            int val = (int) contours.get(i).toArray()[j].y;
            averageY[i] += val;
        }
        averageY[i] /= contours.get(i).total();
        //System.out.println(i+") "+averageY[i]);

        if (averageY[i] <= img.height() / 2 && //We consider just up half of an image
                contours.get(i).total() >= img.width()) //and longer than threshold
            Imgproc.drawContours(harrisTestimg, contours, i, new Scalar(255, 255, 255));
        else
            Imgproc.drawContours(harrisTestimg, contours, i, new Scalar(0, 0, 0));
    }

    MatOfPoint features = new MatOfPoint();
    Imgproc.goodFeaturesToTrack(harrisTestimg, features, 100, 0.00001, 0);

    //We draw just 2 extreme points- first and last
    Point eyebrowsPoints[] = new Point[2];
    for (int i = 0; i < features.toList().size(); i++) {
        if (i == 0) {
            eyebrowsPoints[0] = new Point(harrisTestimg.width() / 2, 0);
            eyebrowsPoints[1] = new Point(harrisTestimg.width() / 2, 0);
        }
        if (features.toArray()[i].x < eyebrowsPoints[0].x
                && features.toArray()[i].y < harrisTestimg.height() / 2) {
            eyebrowsPoints[0] = features.toArray()[i];
        }
        if (features.toArray()[i].x > eyebrowsPoints[1].x
                && features.toArray()[i].y < harrisTestimg.height() / 2) {
            eyebrowsPoints[1] = features.toArray()[i];
        }
    }
    StaticFunctions.drawCross(img, eyebrowsPoints[1], StaticFunctions.Features.EYEBROWS_ENDS);
    StaticFunctions.drawCross(img, eyebrowsPoints[0], StaticFunctions.Features.EYEBROWS_ENDS);
    imwrite("testHaris.jpg", img);
    if (rightEyeFlag) {
        EyeRegion.rightInnerEyebrowsCorner = eyebrowsPoints[0];
        EyeRegion.rightInnerEyebrowsCorner.x += Eye.rightRect.x;
        EyeRegion.rightInnerEyebrowsCorner.y += Eye.rightRect.y;

        EyeRegion.rightOuterEyebrowsCorner = eyebrowsPoints[1];
        EyeRegion.rightOuterEyebrowsCorner.x += Eye.rightRect.x;
        EyeRegion.rightOuterEyebrowsCorner.y += Eye.rightRect.y;
    } else {
        EyeRegion.leftInnerEyebrowsCorner = eyebrowsPoints[1];
        EyeRegion.leftInnerEyebrowsCorner.x += Eye.leftRect.x;
        EyeRegion.leftInnerEyebrowsCorner.y += Eye.leftRect.y;

        EyeRegion.leftOuterEyebrowsCorner = eyebrowsPoints[0];
        EyeRegion.leftOuterEyebrowsCorner.x += Eye.leftRect.x;
        EyeRegion.leftOuterEyebrowsCorner.y += Eye.leftRect.y;
    }
}

From source file:emotion.StaticFunctions.java

public static Mat gabor(Mat image) {
    Mat img = image.clone();

    double ksize = 15;
    double sigme = 4;
    double gamma = 1;
    double psi = 50;
    int lambd[] = new int[] { 5, 6, 7, 10/*,15,13,2*/ };
    double theta[] = new double[] { 180, 200 };
    ArrayList<Mat> kernels = new ArrayList<>();
    for (int i = 0; i < theta.length; i++) {
        for (int j = 0; j < lambd.length; j++) {
            kernels.add(Imgproc.getGaborKernel(new Size(ksize, ksize), sigme, theta[i], lambd[j], gamma, psi,
                    CvType.CV_32F));//  w w w.j  a  v a2s .  c o m
        }
    }

    Mat result = new Mat(img.height(), img.width(), img.type(), new Scalar(0, 0, 0));
    for (Mat kernel : kernels) {
        Mat temp = new Mat(img.height(), img.width(), img.type(), new Scalar(0, 0, 0));
        Imgproc.filter2D(img, temp, -1, kernel);
        Core.add(result, temp, result);
    }

    //imwrite("gaborResult.jpg",result);
    return result;
}

From source file:facerecognition.sample1.java

private static Rect find_enclosing_rectangle(double[][] puntos, File image_file) {

    Mat image = Imgcodecs.imread(image_file.getAbsolutePath());
    int i = 0;/*w w w .j ava2 s .  co  m*/
    Mat img2 = image.clone();
    for (CascadeClassifier faceDetector : faceDetectors) {

        // Detect faces in the image.
        // MatOfRect is a special container class for Rect.
        MatOfRect faceDetections = new MatOfRect();
        faceDetector.detectMultiScale(image, faceDetections);

        System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));

        // Draw a bounding box around each face.
        //            double percent = 0.4;
        for (Rect rect : faceDetections.toArray()) {
            Rect piv = rect.clone();
            //  falta expandir
            int h = piv.height, w = piv.width;
            piv.x -= w * percent / 2;
            piv.y -= h * percent / 2;
            piv.height *= (1 + percent);
            piv.width *= (1 + percent);

            //            Mat croped = new Mat(image, rect);
            //             Imgcodecs.imwrite("face"+(++i)+".png", croped);
            Imgproc.rectangle(img2, new Point(rect.x, rect.y),
                    new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));

            int r = 10;
            boolean dentro = true;
            for (double[] punto : puntos) {
                //                    Imgproc.circle(img2, new Point(rect.x, rect.y), r, new Scalar(0, 255, 0));

                if (piv.contains(new Point(punto)) == false) {
                    dentro = false;
                    //                        break;
                }
            }
            if (dentro) {
                //                    Imgcodecs.imwrite(urlHelen + "\\face" + (Math.random()) + ".png", img2);
                return piv;
            }
        }

    }
    //        Imgcodecs.imwrite( urlHelen + "\\face"+(Math.random())+".png", img2);

    return null;
}

From source file:facerecognition.sample1.java

private static void draw_initial_points() {
    //        PrintWriter pw = null;
    //        try {
    faceDetectors = new CascadeClassifier[] { new CascadeClassifier("haarcascade_frontalface_alt_tree.xml"),
            new CascadeClassifier("haarcascade_frontalface_alt2.xml"),
            new CascadeClassifier("haarcascade_profileface.xml") };
    File[] image_files = get_images();
    int index = 0;
    int contador = 0;
    //            File resumen = new File(urlHelen + "\\summary.sum");
    //            pw = new PrintWriter(resumen);

    double[][] mask = leer_mask();

    for (File image_file : image_files) {
        System.out.println("Analizando imagen " + (++index) + " de " + image_files.length);
        //            BufferedImage img = convert_to_BufferedImage(image_file);
        //                File puntos_file = get_puntos_file(image_file);
        //                double[][] puntos = LWF.leerpuntos(puntos_file);

        Mat image = Imgcodecs.imread(image_file.getAbsolutePath());
        Mat img2 = image.clone();

        for (CascadeClassifier faceDetector : faceDetectors) {

            // Detect faces in the image.
            // MatOfRect is a special container class for Rect.
            MatOfRect faceDetections = new MatOfRect();
            faceDetector.detectMultiScale(image, faceDetections);

            System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));

            // Draw a bounding box around each face.
            for (Rect rect : faceDetections.toArray()) {
                Rect piv = rect.clone();
                //  falta expandir
                int h = piv.height, w = piv.width;
                piv.x -= w * percent / 2;
                piv.y -= h * percent / 2;
                piv.height *= (1 + percent);
                piv.width *= (1 + percent);

                //            Mat croped = new Mat(image, rect);
                //             Imgcodecs.imwrite("face"+(++i)+".png", croped);
                Imgproc.rectangle(img2, new Point(piv.x, piv.y),
                        new Point(piv.x + piv.width, piv.y + piv.height), new Scalar(0, 255, 0));

                for (double[] punto : mask) {
                    Imgproc.circle(img2, new Point(piv.x + piv.width * punto[0], piv.y + piv.height * punto[1]),
                            5, new Scalar(0, 255, 0));
                }/*from   w w w.  ja v a2s  .com*/
            }

        }
        //            pw.close();
        Imgcodecs.imwrite(urlHelen + "\\face" + (Math.random()) + ".png", img2);

    }

}

From source file:fi.conf.tabare.ARDataProvider.java

private void detect() {

    //Mat composite_image;
    Mat input_image = new Mat();
    Mat undistorted_image = new Mat();
    Mat circles = new Mat();
    MatOfKeyPoint mokp = new MatOfKeyPoint();
    Mat cameraMatrix = null;//from   w ww.j  a  va  2  s . c om

    //List<Mat> channels = new LinkedList<>();

    //Loop
    while (running) {
        try {
            if (inputVideo.read(input_image)) {
                Mat preview_image = null;

                if (selectedView == View.calib)
                    preview_image = input_image.clone();

                //Imgproc.cvtColor(input_image, input_image, Imgproc.COLOR_RGB2HSV);
                //Core.split(input_image, channels);

                Imgproc.cvtColor(input_image, input_image, Imgproc.COLOR_BGR2GRAY);

                //Imgproc.equalizeHist(input_image, input_image);

                input_image.convertTo(input_image, -1, params.contrast, params.brightness); //image*contrast[1.0-3.0] + brightness[0-255]

                doBlur(input_image, input_image, params.blur, params.blurAmount);

                if (selectedView == View.raw)
                    preview_image = input_image.clone();

                if (params.enableDistortion) {

                    if (cameraMatrix == null)
                        cameraMatrix = Imgproc.getDefaultNewCameraMatrix(Mat.eye(3, 3, CvType.CV_64F),
                                new Size(input_image.width(), input_image.height()), true);

                    Imgproc.warpAffine(input_image, input_image, shiftMat, frameSize);

                    if (undistorted_image == null)
                        undistorted_image = new Mat((int) frameSize.width * 2, (int) frameSize.height * 2,
                                CvType.CV_64F);

                    Imgproc.undistort(input_image, undistorted_image, cameraMatrix, distCoeffs);

                    input_image = undistorted_image.clone();

                    if (selectedView == View.dist)
                        preview_image = input_image.clone();

                }

                //               if(background == null) background = input_image.clone();         
                //               if(recaptureBg){
                //                  backgSubstractor.apply(background, background);
                //                  System.out.println(background.channels() + " " + background.size() );
                //                  System.out.println(input_image.channels() + " " + input_image.size() );
                //                  recaptureBg = false;
                //               }
                //               if(dynamicBGRemoval){
                //                  //Imgproc.accumulateWeighted(input_image, background, dynamicBGAmount);
                //                  //Imgproc.accumulateWeighted(input_image, background, 1.0f);
                //                  //Core.subtract(input_image, background, input_image);
                //                  //Core.bitwise_xor(input_image, background, input_image);
                //
                //                  doBlur(input_image, background, Blur.normal_7x7, 0); //Blur a little, to get nicer result when substracting
                //                  backgSubstractor.apply(background, background, dynamicBGAmount);
                //               }
                //               if(background != null) Core.add(input_image, background, input_image);

                if (params.blobTracking) {
                    Mat blobs_image = input_image.clone();

                    Imgproc.threshold(blobs_image, blobs_image, params.blobThreshold, 254,
                            (params.blobThInverted ? Imgproc.THRESH_BINARY_INV : Imgproc.THRESH_BINARY));

                    Size kernelSize = null;

                    switch (params.blobMorpthKernelSize) {
                    case size_3x3:
                        kernelSize = new Size(3, 3);
                        break;
                    case size_5x5:
                        kernelSize = new Size(5, 5);
                        break;
                    case size_7x7:
                        kernelSize = new Size(7, 7);
                        break;
                    case size_9x9:
                        kernelSize = new Size(9, 9);
                        break;
                    }

                    int kernelType = -1;

                    switch (params.blobMorphKernelShape) {
                    case ellipse:
                        kernelType = Imgproc.MORPH_ELLIPSE;
                        break;
                    case rect:
                        kernelType = Imgproc.MORPH_RECT;
                        break;
                    default:
                        break;
                    }

                    switch (params.blobMorphOps) {
                    case dilate:
                        Imgproc.dilate(blobs_image, blobs_image,
                                Imgproc.getStructuringElement(kernelType, kernelSize));
                        break;
                    case erode:
                        Imgproc.erode(blobs_image, blobs_image,
                                Imgproc.getStructuringElement(kernelType, kernelSize));
                        break;
                    default:
                        break;
                    }

                    if (blobFeatureDetector == null)
                        blobFeatureDetector = FeatureDetector.create(FeatureDetector.SIMPLEBLOB);

                    blobFeatureDetector.detect(blobs_image, mokp);
                    blobData.add(mokp);

                    if (selectedView == View.blob)
                        preview_image = blobs_image.clone();

                    blobs_image.release();
                }

                if (params.tripTracking) {

                    Mat trips_image = undistorted_image.clone();

                    if (params.tripEnableThresholding)
                        if (params.tripAdaptThreshold) {
                            Imgproc.adaptiveThreshold(trips_image, trips_image, 255,
                                    (params.tripThInverted ? Imgproc.THRESH_BINARY_INV : Imgproc.THRESH_BINARY),
                                    Imgproc.ADAPTIVE_THRESH_MEAN_C, 5, params.tripThreshold * 0.256f);
                        } else {
                            Imgproc.threshold(trips_image, trips_image, params.tripThreshold, 255,
                                    (params.tripThInverted ? Imgproc.THRESH_BINARY_INV
                                            : Imgproc.THRESH_BINARY));
                        }

                    switch (params.tripMorphOps) {
                    case dilate:
                        Imgproc.dilate(trips_image, trips_image,
                                Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(3, 3)));
                        break;
                    case erode:
                        Imgproc.erode(trips_image, trips_image,
                                Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(3, 3)));
                        break;
                    default:
                        break;
                    }

                    //Imgproc.HoughCircles(tres, circ, Imgproc.CV_HOUGH_GRADIENT, 1, tres.height()/8, 80, 1+p.par4, p.par5, p.par6);
                    Imgproc.HoughCircles(trips_image, circles, Imgproc.CV_HOUGH_GRADIENT, params.tripDP,
                            params.tripCenterDist, params.tripCannyThresh, params.tripAccumThresh,
                            params.tripRadMin, params.tripRadMax);

                    for (int i = 0; i < circles.cols(); i++) {

                        double[] coords = circles.get(0, i);

                        if (coords == null || coords[0] <= 1 || coords[1] <= 1)
                            continue; //If the circle is off the limits, or too small, don't process it.

                        TripcodeCandidateSample tc = new TripcodeCandidateSample(undistorted_image, coords);

                        if (tc.isValid())
                            tripcodeData.add(tc);

                    }

                    if (selectedView == View.trip)
                        preview_image = trips_image.clone();
                    trips_image.release();

                }

                if (preview_image != null) {
                    camPreviewPanel.updatePreviewImage(preview_image);
                    preview_image.release();
                }

            } else {
                System.out.println("frame/cam failiure!");
            }

        } catch (Exception e) {
            e.printStackTrace();
            running = false;
        }

        //FPS calculations
        if (camPreviewPanel != null) {
            long t = System.currentTimeMillis();
            detectTime = (t - lastFrameDetectTime);
            lastFrameDetectTime = t;
            camPreviewPanel.updateDetectTime(detectTime);
        }

    }

    //De-init
    circles.release();
    undistorted_image.release();
    input_image.release();
    inputVideo.release();
    shiftMat.release();
}

From source file:houghtransform.transform_process.MyTransform.java

@Override
public void houghTransform(Mat edges) {
    Mat _edges = edges.clone();

    double radian = Math.PI / 180;
    int degrees = (int) Math.floor(theta * 180 / Math.PI + 0.5);

    int w = _edges.cols();
    int h = _edges.rows();

    _edges.convertTo(_edges, CvType.CV_64FC3);
    int size = w * h;
    double[] img_data = new double[size];
    _edges.get(0, 0, img_data); // Gets all pixels

    _img_w = w; //Number of columns
    _img_h = h; //Number of lines

    //Create the accumulator
    double hough_h = ((Math.sqrt(2.0) * (double) (h > w ? h : w)) / 2.0);
    _accu_h = (int) (hough_h * 2.0); // -r -> +r
    _accu_w = 180;//from   w w w  .j  av  a2  s  . c  o m

    _accu = new int[_accu_h * _accu_w];
    for (int i = 0; i < _accu_h * _accu_w; i++) {
        _accu[i] = 0;
    }

    double center_x = w / 2;
    double center_y = h / 2;

    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
            if (img_data[(y * w) + x] > 250) {
                for (int t = 0; t < 180; t = t + degrees) {
                    // y = x * cos( theta ) + y * sin( theta )
                    double r = (((double) x - center_x) * Math.cos((double) t * radian))
                            + (((double) y - center_y) * Math.sin((double) t * radian));
                    _accu[(int) ((Math.floor(r + hough_h) * 180.0)) + t]++;
                }
            }
        }
    }

    ArrayList<Point> lines = new ArrayList<>();

    if (_accu.length == 0)
        try {
            throw new IOException("MyTransform: _accu == 0");
        } catch (IOException ex) {
            System.out.println(ex);
        }

    for (int r = 0; r < _accu_h; r++) {
        for (int t = 0; t < _accu_w; t++) {
            // Searching in the accumulator a value greater
            //or equal to the set threshold
            if (((int) _accu[(r * _accu_w) + t]) >= threshold) {
                // Is this point a local maxima (9x9)
                int max = _accu[(r * _accu_w) + t];
                ////////////////////////////////
                for (int ly = -4; ly <= 4; ly++) {
                    for (int lx = -4; lx <= 4; lx++) {
                        if (((ly + r) >= 0 && (ly + r) < _accu_h) && ((lx + t) >= 0 && (lx + t) < _accu_w)) {
                            if ((int) _accu[((r + ly) * _accu_w) + (t + lx)] > max) {
                                max = _accu[((r + ly) * _accu_w) + (t + lx)];
                                ly = lx = 5;
                            }
                        }
                    }
                }
                /////////////////////////////////
                if (max > (int) _accu[(r * _accu_w) + t])
                    continue;

                Point point = new Point();
                point.x = r;
                point.y = t * radian;
                lines.add(point);
            }
        }
    }
    _lines = lines;
}