Example usage for org.opencv.imgproc Imgproc erode

List of usage examples for org.opencv.imgproc Imgproc erode

Introduction

In this page you can find the example usage for org.opencv.imgproc Imgproc erode.

Prototype

public static void erode(Mat src, Mat dst, Mat kernel) 

Source Link

Usage

From source file:MainEroding.java

public static void main(String[] args) {

    try {/*from   w w  w . ja va2s  . co  m*/

        int erosion_size = 2;
        //int dilation_size = 5;

        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        Mat source = Highgui.imread("D://teste.png", Highgui.CV_LOAD_IMAGE_COLOR);

        Mat destination = new Mat(source.rows(), source.cols(), source.type());

        destination = source;

        Mat element = Imgproc.getStructuringElement(Imgproc.MORPH_RECT,
                new Size(2 * erosion_size + 1, 2 * erosion_size + 1));

        Imgproc.erode(source, destination, element);

        Highgui.imwrite("D://Erosion.jpg", destination);

    } catch (Exception e) {
        System.out.println("Exception: " + e.getMessage());
    }

}

From source file:Questao2.java

void minimo() {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    String url = escolherUrl();//from w w  w .  java 2  s.  c om
    /**
     * Transforma imagem em matriz para facilitar manipulacao
     */
    Mat img = Imgcodecs.imread(url);
    /**
     * Cria matriz de destino
     */
    Mat dst = new Mat();
    /**
     * Cria matriz com o valor 1 em todos os pixels de
     * tamanho definido pelo usuario
     */
    System.out.println("Digite as dimenses da mscara: ");
    System.out.print("X: ");
    int mx = in.nextInt();
    System.out.print("Y: ");
    int my = in.nextInt();
    Mat one = Mat.ones(mx, my, CvType.CV_32F);
    /**
     * Aplica o filtro minimo
     * erode(imagem original, imagem destino, matriz de mascara)
     */
    Imgproc.erode(img, dst, one);
    /**
     * Salva resultado em minimo.jpg
     */
    Imgcodecs.imwrite("minimo.jpg", dst);
    showResult("minimo.jpg");
}

From source file:br.cefetmg.lsi.opencv.multipleObjectTracking.processing.MultipleObjectTracking.java

License:Open Source License

private void morphOps(Mat thresh) {
    //create structuring element that will be used to "dilate" and "erode" image.
    //the element chosen here is a 3px by 3px rectangle

    Mat erodeElement = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(3, 3));
    //dilate with larger element so make sure object is nicely visible
    Mat dilateElement = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(8, 8));

    Imgproc.erode(thresh, thresh, erodeElement);
    Imgproc.erode(thresh, thresh, erodeElement);

    Imgproc.dilate(thresh, thresh, dilateElement);
    Imgproc.dilate(thresh, thresh, dilateElement);
}

From source file:by.zuyeu.deyestracker.core.detection.task.DetectPupilsTask.java

@Override
public Point call() throws Exception {
    long startTime = System.nanoTime();

    final Mat imageHSV = new Mat(frame.size(), Core.DEPTH_MASK_8U);
    Imgproc.cvtColor(frame, imageHSV, Imgproc.COLOR_BGR2GRAY);

    Imgproc.erode(imageHSV, imageHSV, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, STRUCT_ELEMENT_SIZE));
    Imgproc.dilate(imageHSV, imageHSV, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, STRUCT_ELEMENT_SIZE));
    Imgproc.GaussianBlur(imageHSV, imageHSV, STRUCT_ELEMENT_SIZE, GAUS_BLUR_DELTA);

    Core.MinMaxLocResult mmG = Core.minMaxLoc(imageHSV);

    long endTime = System.nanoTime();
    LOG.debug("pupil detected = {}", mmG.minLoc);
    LOG.debug("detection time: {} ms", (float) (endTime - startTime) / 1000000);
    return mmG.minLoc;
}

From source file:Clases.Segmentador.java

public Mat eriosionarImg(Mat umbralizada) {
    Mat dste = umbralizada.clone();/*ww  w .  j  a v a2 s  .c  om*/
    int erosion_size = 5;
    Size s = new Size(2 * erosion_size + 1, 2 * erosion_size + 1);
    Point p = new Point(erosion_size, erosion_size);
    Mat element = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, s, p);
    Imgproc.erode(umbralizada, dste, element);
    return dste;
}

From source file:classes.FloodFiller.java

private void fillFrom(Point seed, int lo, int up, Scalar backgroundColor, Scalar contourFillingColor) {

    Mat object = ObjectGenerator.extract(image, seed.x, seed.y, 10, 10);
    this.meanColor = Core.mean(object);

    Rect ccomp = new Rect();
    Mat mask = Mat.zeros(image.rows() + 2, image.cols() + 2, CvType.CV_8UC1);

    int connectivity = 4;
    int newMaskVal = 255;
    int ffillMode = 1;

    int flags = connectivity + (newMaskVal << 8) + (ffillMode == 1 ? Imgproc.FLOODFILL_FIXED_RANGE : 0);

    Scalar newVal = new Scalar(0.299, 0.587, 0.114);

    Imgproc.threshold(mask, mask, 1, 128, Imgproc.THRESH_BINARY);

    filledArea = Imgproc.floodFill(image.clone(), mask, seed, newVal, ccomp, new Scalar(lo, lo, lo),
            new Scalar(up, up, up), flags);

    //        Highgui.imwrite("mask.png", mask);
    ImageUtils.saveImage(mask, "mask.png", request);

    morphologicalImage = new Mat(image.size(), CvType.CV_8UC3);

    Mat element = new Mat(3, 3, CvType.CV_8U, new Scalar(1));

    ArrayList<Mat> mask3 = new ArrayList<Mat>();
    mask3.add(mask);//from ww w .  j a va 2 s.  co m
    mask3.add(mask);
    mask3.add(mask);
    Core.merge(mask3, mask);

    // Applying morphological filters
    Imgproc.erode(mask, morphologicalImage, element);
    Imgproc.morphologyEx(morphologicalImage, morphologicalImage, Imgproc.MORPH_CLOSE, element,
            new Point(-1, -1), 9);
    Imgproc.morphologyEx(morphologicalImage, morphologicalImage, Imgproc.MORPH_OPEN, element, new Point(-1, -1),
            2);
    Imgproc.resize(morphologicalImage, morphologicalImage, image.size());

    //        Highgui.imwrite("morphologicalImage.png", morphologicalImage);
    ImageUtils.saveImage(morphologicalImage, "morphologicalImage.png", request);

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

    Core.split(mask, mask3);
    Mat binarymorphologicalImage = mask3.get(0);

    Imgproc.findContours(binarymorphologicalImage.clone(), contours, new Mat(), Imgproc.RETR_EXTERNAL,
            Imgproc.CHAIN_APPROX_NONE);

    contoursImage = new Mat(image.size(), CvType.CV_8UC3, backgroundColor);

    int thickness = -1; // Thicknes should be lower than zero in order to drawn the filled contours
    Imgproc.drawContours(contoursImage, contours, -1, contourFillingColor, thickness); // Drawing all the contours found
    //        Highgui.imwrite("allContoursImage.png", contoursImage);
    ImageUtils.saveImage(contoursImage, "allContoursImage.png", request);

    if (contours.size() > 1) {

        int minContourWith = 20;
        int minContourHeight = 20;
        int maxContourWith = 6400 / 2;
        int maxContourHeight = 4800 / 2;

        contours = filterContours(contours, minContourWith, minContourHeight, maxContourWith, maxContourHeight);
    }

    if (contours.size() > 0) {

        MatOfPoint biggestContour = contours.get(0); // getting the biggest contour
        contourArea = Imgproc.contourArea(biggestContour);

        if (contours.size() > 1) {
            biggestContour = Collections.max(contours, new ContourComparator()); // getting the biggest contour in case there are more than one
        }

        Point[] points = biggestContour.toArray();
        path = "M " + (int) points[0].x + " " + (int) points[0].y + " ";
        for (int i = 1; i < points.length; ++i) {
            Point v = points[i];
            path += "L " + (int) v.x + " " + (int) v.y + " ";
        }
        path += "Z";

        biggestContourImage = new Mat(image.size(), CvType.CV_8UC3, backgroundColor);

        Imgproc.drawContours(biggestContourImage, contours, 0, contourFillingColor, thickness);

        //            Highgui.imwrite("biggestContourImage.png", biggestContourImage);
        ImageUtils.saveImage(biggestContourImage, "biggestContourImage.png", request);

        Mat maskForColorExtraction = biggestContourImage.clone();

        if (isWhite(backgroundColor)) {
            Imgproc.dilate(maskForColorExtraction, maskForColorExtraction, new Mat(), new Point(-1, -1), 3);
        } else {
            Imgproc.erode(maskForColorExtraction, maskForColorExtraction, new Mat(), new Point(-1, -1), 3);
        }

        //            Highgui.imwrite("maskForColorExtraction.png", maskForColorExtraction);
        ImageUtils.saveImage(maskForColorExtraction, "maskForColorExtraction.png", request);

        Mat extractedColor = new Mat();

        if (isBlack(backgroundColor) && isWhite(contourFillingColor)) {
            Core.bitwise_and(maskForColorExtraction, image, extractedColor);

        } else {
            Core.bitwise_or(maskForColorExtraction, image, extractedColor);
        }

        //            Highgui.imwrite("extractedColor.png", extractedColor);
        ImageUtils.saveImage(extractedColor, "extractedColor.png", request);

        computedSearchWindow = Imgproc.boundingRect(biggestContour);
        topLeftCorner = computedSearchWindow.tl();

        Rect croppingRect = new Rect(computedSearchWindow.x, computedSearchWindow.y,
                computedSearchWindow.width - 1, computedSearchWindow.height - 1);

        Mat imageForTextRecognition = new Mat(extractedColor.clone(), croppingRect);
        //            Highgui.imwrite(outImageName, imageForTextRecognition);
        ImageUtils.saveImage(imageForTextRecognition, outImageName, request);

        //            
        //
        //            Mat data = new Mat(imageForTextRecognition.size(), CvType.CV_8UC3, backgroundColor);
        //            imageForTextRecognition.copyTo(data);
        //            data.convertTo(data, CvType.CV_8UC3);
        //
        //            // The meanColor variable represents the color in the GBR space, the following line transforms this to the RGB color space, which
        //            // is assumed in the prepareImage method of the TextRecognitionPreparer class
        //            Scalar userColor = new Scalar(meanColor.val[2], meanColor.val[1], meanColor.val[0]);
        //
        //            ArrayList<String> recognizableImageNames = TextRecognitionPreparer.generateRecognizableImagesNames(data, backgroundColor, userColor);
        //            for (String imageName : recognizableImageNames) {
        //
        //                try {
        //                    // First recognition step
        //                    String recognizedText = TextRecognizer.recognize(imageName, true).trim();
        //                    if (recognizedText != null && !recognizedText.isEmpty()) {
        //                        recognizedStrings.add(recognizedText);
        //                    }
        //                    // Second recognition step
        //                    recognizedText = TextRecognizer.recognize(imageName, false).trim();
        //                    if (recognizedText != null && !recognizedText.isEmpty()) {
        //                        recognizedStrings.add(recognizedText);
        //                    }
        //                    
        //                } catch (Exception e) {
        //                }
        //            }
        //            
        ////            ArrayList<BufferedImage> recognizableBufferedImages = TextRecognitionPreparer.generateRecognizableBufferedImages(data, backgroundColor, userColor);
        ////            for (BufferedImage bufferedImage : recognizableBufferedImages) {
        ////                try {
        ////                    // First recognition step
        ////                    String recognizedText = TextRecognizer.recognize(bufferedImage, true).trim();
        ////                    if (recognizedText != null && !recognizedText.isEmpty()) {
        ////                        recognizedStrings.add(recognizedText);
        ////                    }
        ////                    // Second recognition step
        ////                    recognizedText = TextRecognizer.recognize(bufferedImage, false).trim();
        ////                    if (recognizedText != null && !recognizedText.isEmpty()) {
        ////                        recognizedStrings.add(recognizedText);
        ////                    }
        ////                    
        ////                } catch (Exception e) {
        ////                }
        ////            }
        //
        //            
        //            

        // compute all moments
        Moments mom = Imgproc.moments(biggestContour);
        massCenter = new Point(mom.get_m10() / mom.get_m00(), mom.get_m01() / mom.get_m00());

        // draw black dot
        Core.circle(contoursImage, massCenter, 4, contourFillingColor, 8);
    }

}

From source file:classes.ObjectFinder.java

private void applyMorphologicalFilters() {
    Mat element = new Mat(3, 3, CvType.CV_8U, new Scalar(1));
    Imgproc.erode(thresholdedBackprojection, morphologicalImage, element);
    Imgproc.morphologyEx(morphologicalImage, morphologicalImage, Imgproc.MORPH_CLOSE, element,
            new Point(-1, -1), 2);
    Imgproc.morphologyEx(morphologicalImage, morphologicalImage, Imgproc.MORPH_OPEN, element, new Point(-1, -1),
            2);/*from   www .  j  a  v a2s.  c om*/
}

From source file:com.astrocytes.core.operationsengine.CoreOperations.java

License:Open Source License

/**
 * Applies morphological erosion.//from  w  ww  .  ja  v  a 2  s  .c  om
 *
 * @param src - source image.
 * @param radius - radius of structure element.
 * @return eroded image.
 */
public static Mat erode(Mat src, int radius) {
    Mat dest = new Mat();
    int kernelSize = radius * 2 + 1;
    Mat kernel = getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(kernelSize, kernelSize),
            new Point(radius, radius));
    Imgproc.erode(src, dest, kernel);
    return dest;
}

From source file:com.davidmiguel.gobees.monitoring.algorithm.processors.Morphology.java

License:Open Source License

@Override
public Mat process(@NonNull Mat frame) {
    if (frame.empty()) {
        Log.e("Invalid input frame.");
        return null;
    }//from  w w w .  ja  va2  s.  com
    Mat tmp = frame.clone();
    // Step 1: erode to remove legs
    Imgproc.erode(tmp, tmp, KERNEL3);
    // Step 2: dilate to join bodies and heads
    Imgproc.dilate(tmp, tmp, KERNEL2);
    for (int i = 0; i < REPETITIONS_DILATE; i++) {
        Imgproc.dilate(tmp, tmp, kernelDilate);
    }
    // Step 3: erode to recover original size
    Imgproc.erode(tmp, tmp, KERNEL1);
    for (int i = 0; i < REPETITIONS_ERODE; i++) {
        Imgproc.erode(tmp, tmp, kernelErode);
    }
    return tmp;
}

From source file:com.example.root.dipproj.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            File f = new File(Environment.getExternalStorageDirectory().toString());
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;//from   w  ww.j  a  v a  2  s  .  c o m
                    break;
                }
            }
            try {
                Bitmap bitmap;
                BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
                viewImage.setImageBitmap(bitmap);
                String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix"
                        + File.separator + "default";
                f.delete();
                OutputStream outFile = null;
                File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                try {
                    outFile = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                    outFile.flush();
                    outFile.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == 2) {
            Uri selectedImage = data.getData();
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            String picturePath = c.getString(columnIndex);
            c.close();
            Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
            Log.w("path of image", picturePath + "");
            Mat imgMat = new Mat();
            Mat imgMat2 = new Mat();
            Mat imgMat3 = new Mat();
            Utils.bitmapToMat(thumbnail, imgMat);
            Imgproc.cvtColor(imgMat, imgMat, Imgproc.COLOR_RGB2GRAY);
            org.opencv.core.Size s = new Size(3, 3);
            Imgproc.createCLAHE();
            Imgproc.GaussianBlur(imgMat, imgMat, s, 2);
            Imgproc.erode(imgMat, imgMat2, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(2, 2)));
            Imgproc.dilate(imgMat2, imgMat3, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(2, 2)));
            Imgproc.Sobel(imgMat, imgMat, CvType.CV_8UC1, 1, 0);
            Core.absdiff(imgMat, imgMat3, imgMat);
            Imgproc.threshold(imgMat, imgMat, 123, 255, Imgproc.THRESH_OTSU);
            Utils.matToBitmap(imgMat, thumbnail);
            viewImage.setImageBitmap(thumbnail);
            saveBitmaptoSDCard(thumbnail);
        }
    }
}