Example usage for org.opencv.core Scalar Scalar

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

Introduction

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

Prototype

public Scalar(double v0, double v1, double v2) 

Source Link

Usage

From source file:Comun.Imagen.java

public String dividirImagen(String nombreCarpeta) {
    StringBuilder SB = new StringBuilder();

    //Crea la carpeta donde alojar las imagenes
    this.nombreCarpeta = nombreCarpeta;
    File carpeta = new File(nombreCarpeta);
    if (carpeta.mkdir()) {
        Mat imgAux = new Mat();
        //Convertir la imagen en escala de grises a binario
        threshold(imagen, imgAux, 128, 255, THRESH_BINARY | THRESH_OTSU);

        //Dibuja los bordes
        double umbral = 100;
        Canny(imgAux, imgAux, umbral, umbral * 2);

        //Lista que guarda los puntos de los contornos
        LinkedList<MatOfPoint> contornos = new LinkedList<>();
        Mat jerarquia = new Mat();

        //Detecto los contornos
        findContours(imgAux, contornos, jerarquia, RETR_TREE, CHAIN_APPROX_SIMPLE);

        Rect contorno;//from w w w  .  j a  v  a2s  .c o m

        if (!contornos.isEmpty()) {
            SB.append("Se han encontrado ").append(contornos.size()).append(" contornos -");

            double areaProm = 0;
            for (int i = 0; i < contornos.size(); i++) {
                contorno = boundingRect(contornos.get(i));
                areaProm += contorno.area();
            }

            //Asigna que para ser un contorno valido debe ser mayor al 10% del segundo mayor
            areaProm = (areaProm / contornos.size()) * 0.25;
            ArrayList<Rect> contornosFiltrados = new ArrayList<>();

            //Guarda las letras detectadas
            for (int i = 0; i < contornos.size(); i++) {

                contorno = boundingRect(contornos.get(i));
                //Verifica que supere el limite
                if (contorno.area() > areaProm) {
                    contornosFiltrados.add(contorno);
                }
            }
            //Ordeno los contornos de mayor a menor
            Mergesort merge = new Mergesort(contornosFiltrados);
            merge.ordenar();
            contornosFiltrados = merge.getV();

            //Filtro solo los contornos que no se superponen con otro
            ArrayList<Rect> contornosFinal = new ArrayList<>();
            boolean bandera = false;
            for (Rect recta : contornosFiltrados) {
                for (Rect c : contornosFinal) {
                    if (c.contains(recta.tl()) || c.contains(recta.br())) {
                        bandera = true;
                        break;
                    }
                }
                if (!bandera) {
                    //Agrego el contorno a la lista final de contornos
                    contornosFinal.add(recta);
                    //Guardo la imagen en la carpeta
                    this.guardarImagen(new Mat(imagen, recta), contornosFinal.size());

                    //La marca en la imagen principal
                    rectangle(imagen, new Point(recta.x, recta.y),
                            new Point(recta.x + recta.width, recta.y + recta.height), new Scalar(0, 255, 0));
                }
                bandera = false;
            }

            SB.append("Contornos Validos: ").append(contornosFinal.size());

        } else {
            SB.append("No se ha encontrado ningun contorno");
        }
    } else {
        SB.append("No se pudo crear la carpeta");
    }
    this.guardarImagen(imagen, 0);
    return SB.toString();
}

From source file:contador_de_moedas.Circulo.java

private Mat doCirciloHough(Mat imgIn) {
    int valor = 0;
    baseImageList();/*from  w w  w.ja v a 2s .c  om*/
    Reconhecimento _reco;
    Imgproc.cvtColor(imgIn, imgIn, Imgproc.COLOR_BGR2GRAY);
    /*Imgproc.erode(imgIn, imgIn, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(2, 2)));
     Imgproc.dilate(imgIn, imgIn, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(2, 2)));*/

    double min_dist_Centro = imgIn.rows() / 8.0;
    /*
     Imgproc.HoughCircles(imageB, circles, method, dp, minDist, param1, param2, minRadius, maxRadius)
     imageB: Imagem de entrada (tons de cinza)
     circles: um vector que armazena conjuntos de 3 valores: Xc, Yc, r para cada crculo detectado.
     method: CV_HOUGH_GRADIENT definir o mtodo de deteco. Atualmente, esse  o nico disponvel em OpenCV
     dp: (1) A razo inversa da resoluo
     min_dist: (imgIn.rows / 8 ) A distncia mnima entre centros detectados
     param1: (200 limite superior para o detector de bordas Canny interna) limite superior para o detector de bordas Canny interna
     param2: (100* Limiar para deteco de centro)Limiar para deteco de centro.
     minRadius: (0) raio minimo a ser detectado. Se for desconhecida, colocar zero como padrao.
     maxRadius: (maxRadius) raio maximo a ser detectado. Se desconhecida, colocar zero como padrao   
     */
    Imgproc.HoughCircles(imgIn, circles, Imgproc.CV_HOUGH_GRADIENT, 1, min_dist_Centro, param1, param2,
            minRadius, maxRadius);

    rowsCols[0] = circles.rows();
    rowsCols[1] = circles.cols();

    for (int i = 0; i < circles.cols(); i++) {
        _reco = new Reconhecimento();
        double data[] = circles.get(0, i);
        Point pt = new Point(Math.round(data[0]), Math.round(data[1]));
        int raio = (int) Math.round(data[2]);

        if (data[2] > 20.0 && data[2] < 28.0) {
            valor = 10;
            setSomatorio(getSomatorio() + valor);
        } else if (data[2] > 27.0 && data[2] < 32.0) {
            valor = 5;
            setSomatorio(getSomatorio() + valor);
        } else if (data[2] > 32.0 && data[2] < 33.0) {
            valor = 50;
            setSomatorio(getSomatorio() + valor);
        } else if (data[2] > 33.5 && data[2] < 36.0) {
            valor = 25;
            setSomatorio(getSomatorio() + valor);
        } else if (data[2] > 35.0 && data[2] < 40.0) {
            valor = 100;
            setSomatorio(getSomatorio() + valor);
        }
        resultados.add(" r:" + (int) raio + "   (X:" + (int) pt.x + "-Y:" + (int) pt.y + ") Val: " + valor);
        vetMat[i] = _reco.CriaMascara(pt, data[2], imgIn);
        output = _reco.CalculaHistograma(vetMat[i], imageA);

        /*  System.out.println("histogram\n"+output.dump());
         for (int j = 0; j < vetMatFile.length - 1; j++) {
         Mat ab = vetMatFile[j];
         System.out.println("histogram\n"+vetMatFile[j].dump());
         double distance = Imgproc.compareHist(output, vetMatFile[j], Imgproc.CV_COMP_CORREL);
                
         System.out.print("ok");
         }*/

        if (criaBase) {
            FileWriter arq = null;
            try {
                String nome = "X" + (int) pt.x + "Y" + (int) pt.y + "R" + (int) raio;
                // Imgcodecs.imwrite("baseConhecimento/" + nome + "M.png", vetMat[i]);
                arq = new FileWriter("baseConhecimento/" + nome + ".txt");
                PrintWriter gravarArq = new PrintWriter(arq);
                gravarArq.print(output.dump());
                arq.close();
                // Imgcodecs.imwrite("baseConhecimento/" + nome + ".yml", output);
            } catch (IOException ex) {
                Logger.getLogger(Circulo.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    arq.close();
                } catch (IOException ex) {
                    Logger.getLogger(Circulo.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        Imgproc.circle(imageA, pt, raio, new Scalar(0, 0, 255), 2);
        Imgproc.circle(imageA, pt, 2, new Scalar(0, 255, 0), 1);
    }
    return imageA;
}

From source file:contador_de_moedas.Reconhecimento.java

public Mat CriaMascara(Point pt, double raio, Mat img_Original) {
    // Cria uma img toda preta com as mesmas dimenses da original
    Mat mask = zeros(img_Original.rows(), img_Original.cols(), CV_8U);
    // Cria um circulo branco preenchido
    Imgproc.circle(mask, pt, (int) raio, new Scalar(255, 255, 255), -1, 8, 0);
    return (mask);
}

From source file:cubesolversimulator.VisualInputForm.java

private void getContour() {
    Mat dilate = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(7, 7));

    Imgproc.dilate(edge, edge, dilate);/*from   w  ww. j  ava  2  s  . co  m*/
    Imgproc.dilate(edge, edge, dilate);

    Highgui.imwrite("dilate.jpg", edge);

    List<MatOfPoint> contours = new ArrayList<>();

    Imgproc.findContours(edge, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
    Imgproc.drawContours(contour, contours, -1, new Scalar(255, 255, 255));

    Highgui.imwrite("Contour.jpg", contour);

    img4 = new JLabel("");
    img4.setSize(jPanel7.getSize());
    image4 = new ImageIcon(new ImageIcon("D:\\Project_work\\CubeSolverSimulator\\dilate.jpg").getImage()
            .getScaledInstance(img4.getWidth(), img4.getHeight(), Image.SCALE_FAST));
    img4.setIcon(image4);
    img4.repaint();
    jPanel7.add(img4);
    jPanel7.repaint();
    findRect(contours);
}

From source file:cubesolversimulator.VisualInputForm.java

private void findRect(List<MatOfPoint> contours) {
    int j = 0;//from w w w. j  av  a2  s  .  c  o  m
    temp = blured.clone();
    List<Rect> roi = new ArrayList<>();
    for (int i = 0; i < contours.size(); i++) {
        Rect rect = Imgproc.boundingRect(contours.get(i));
        if (rect.height > 60 && rect.width > 60 && rect.height < 140 && rect.width < 140
                && (rect.height <= (rect.width + 30) || rect.height >= (rect.width - 30))) {
            Core.rectangle(temp, new Point(rect.x, rect.y),
                    new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0), 2);
            j++;
            roi.add(rect);
            // System.out.println(rect.x+"   "+rect.y);
        }
    }
    Highgui.imwrite("rect.jpg", temp);
    //System.out.println(j+" "+roi.size());
    filterOverlap(roi);
}

From source file:cubesolversimulator.VisualInputForm.java

private void filterOverlap(List<Rect> roi) {
    Mat filtered = blured.clone();//from  w ww.j  a v  a  2 s  . c om
    for (int i = 0; i < roi.size(); i++) {
        for (int j = i + 1; j < roi.size(); j++) {
            if ((roi.get(i).x >= roi.get(j).x - 100 && roi.get(i).x <= roi.get(j).x + 100)
                    && (roi.get(i).y >= roi.get(j).y - 100 && roi.get(i).y <= roi.get(j).y + 100)) {
                if (roi.get(i).area() > roi.get(j).area()) {
                    roi.remove(i);
                } else {
                    roi.remove(j);
                }
            }
        }
    }
    //System.out.println("Final Size: "+roi.size());
    for (int i = 0; i < roi.size(); i++) {
        // System.out.println()
        Rect rect = roi.get(i);
        Core.rectangle(filtered, new Point(rect.x, rect.y),
                new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 255), 2);
    }
    Highgui.imwrite("filteredrect.jpg", filtered);

    img5 = new JLabel("");
    img5.setSize(jPanel2.getSize());
    image5 = new ImageIcon(new ImageIcon("D:\\Project_work\\CubeSolverSimulator\\filteredrect.jpg").getImage()
            .getScaledInstance(img5.getWidth(), img5.getHeight(), Image.SCALE_FAST));
    img5.setIcon(image5);
    img5.repaint();
    jPanel2.add(img5);
    jPanel2.repaint();

    reorderContours(roi);
    findAvg(roi);
}

From source file:cubesolversimulator.VisualInputForm.java

private void findAvg(List<Rect> roi) {
    cols = new int[9];
    for (int i = 0; i < roi.size(); i++) {
        Mat ri = new Mat(blured, roi.get(i));
        ri.convertTo(ri, -1, 1.0);/*w  w  w  . java  2s.c  o  m*/
        Highgui.imwrite("extract" + i + ".jpg", ri);
        Scalar clr = new Scalar(0, 0, 0);
        clr = Core.mean(ri);
        System.out.println("old col: " + clr);
        if (clr.val[0] > 30)
            clr.val[0] = clr.val[0] - 30;
        else
            clr.val[0] = 0;
        //if(clr.val[2]<200)
        //  clr.val[2]=clr.val[2]+20;
        //else
        //  clr.val[0]=0;
        System.out.println("new col: " + clr);
        getDistance(clr, i);
    }
    displayLabel();
}

From source file:cubesolversimulator.VisualInputForm.java

private void getDistance(Scalar clr, int s) {
    double min = 0, dis;
    int col = 0;/*from  w  ww .  java 2 s . co m*/
    Scalar dist = new Scalar(0, 0, 0);
    //initialise standards dynamically        
    Scalar std[] = { new Scalar(200, 0, 0), new Scalar(0, 200, 0), new Scalar(0, 0, 185),
            new Scalar(0, 160, 200), new Scalar(0, 80, 200), new Scalar(200, 200, 200) };
    //blue, green, red, yellow, orange, white
    for (int i = 0; i < std.length; i++) {
        dist.val[0] = clr.val[0] - std[i].val[0];
        dist.val[1] = clr.val[1] - std[i].val[1];
        dist.val[2] = clr.val[2] - std[i].val[2];

        dis = Math.sqrt((dist.val[0] * dist.val[0] + dist.val[1] * dist.val[1] + dist.val[2] * dist.val[2]));

        if (i == 0) {
            min = dis;
            col = i;
        } else if (dis < min) {
            min = dis;
            col = i;
        }
    }
    System.out.println(col);
    cols[s] = col;
}

From source file:cv.FaceDetector.java

License:Open Source License

public BufferedImage detectFace(String imagePath) {
    // Create a face detector from the cascade file in the resources directory.
    String facePropertiesFilePath = getClass().getResource("/lbpcascade_frontalface.xml").getPath();
    CascadeClassifier faceDetector = new CascadeClassifier(facePropertiesFilePath);
    Mat image = Imgcodecs.imread(imagePath);
    // Detect faces in the image.
    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()) {
        Imgproc.rectangle(image, new org.opencv.core.Point(rect.x, rect.y),
                new org.opencv.core.Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
    }//ww  w. j ava2s  .  c  om

    // Return the image
    return matToBufferedImage(image);
}

From source file:de.vion.eyetracking.cameracalib.calibration.opencv.CameraCalibrator.java

private void renderFrame(Mat rgbaFrame) {
    drawPoints(rgbaFrame);/* w  w w.j  a  v a 2s . c o m*/

    Core.putText(rgbaFrame, "Captured: " + this.mCornersBuffer.size(),
            new Point(rgbaFrame.cols() / 3 * 2, rgbaFrame.rows() * 0.1), Core.FONT_HERSHEY_SIMPLEX, 1.0,
            new Scalar(255, 255, 0));
}