List of usage examples for org.opencv.imgproc Imgproc floodFill
public static int floodFill(Mat image, Mat mask, Point seedPoint, Scalar newVal, Rect rect, Scalar loDiff, Scalar upDiff, int flags)
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);/* w w w . jav a 2 s. c om*/ 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.FloodFillFacade.java
public Mat fill(Mat image, Mat mask, int x, int y, Scalar newVal) { Point seedPoint = new Point(x, y); Rect rect = new Rect(); // Scalar newVal = isColored() ? new Scalar(b, g, r) : new Scalar(r * 0.299 + g * 0.587 + b * 0.114); Scalar lowerDifference = new Scalar(lowerDiff, lowerDiff, lowerDiff); Scalar upperDifference = new Scalar(upperDiff, upperDiff, upperDiff); if (range == NULL_RANGE) { lowerDifference = new Scalar(0, 0, 0); upperDifference = new Scalar(0, 0, 0); }/*from w w w . j a v a2 s . co m*/ int flags = connectivity + (newMaskVal << 8) + ((range == FIXED_RANGE ? Imgproc.FLOODFILL_FIXED_RANGE : 0) | 0);//Imgproc.FLOODFILL_MASK_ONLY); int area = 0; if (masked) { area = Imgproc.floodFill(image, mask, seedPoint, newVal, rect, lowerDifference, upperDifference, flags); } else { area = Imgproc.floodFill(image, new Mat(), seedPoint, newVal, rect, lowerDifference, upperDifference, flags); } // Highgui.imwrite("C:\\Users\\Gonzalo\\Documents\\NetBeansProjects\\iVoLVER\\uploads\\image_after_flood_" + cont + ".png", image); // Highgui.imwrite("C:\\Users\\Gonzalo\\Documents\\NetBeansProjects\\iVoLVER\\uploads\\mask_" + cont + ".png", mask); // System.out.println("area: " + area); cont++; return image; }
From source file:qupath.opencv.tools.WandToolCV.java
License:Open Source License
@Override protected Shape createShape(double x, double y, boolean useTiles) { if (mat == null) mat = new Mat(w, w, CvType.CV_8UC3); if (matMask == null) matMask = new Mat(w + 2, w + 2, CvType.CV_8U); if (pLast != null && pLast.distanceSq(x, y) < 4) return new Path2D.Float(); long startTime = System.currentTimeMillis(); QuPathViewer viewer = getViewer();/*from w w w. j a v a 2 s .c o m*/ if (viewer == null) return new Path2D.Float(); double downsample = viewer.getDownsampleFactor(); DefaultImageRegionStore regionStore = viewer.getImageRegionStore(); // Paint the image as it is currently being viewed Graphics2D g2d = imgTemp.createGraphics(); g2d.setColor(Color.BLACK); g2d.fillRect(0, 0, w, w); bounds.setFrame(x - w * downsample * .5, y - w * downsample * .5, w * downsample, w * downsample); g2d.scale(1.0 / downsample, 1.0 / downsample); g2d.translate(-bounds.getX(), -bounds.getY()); regionStore.paintRegionCompletely(viewer.getServer(), g2d, bounds, viewer.getZPosition(), viewer.getTPosition(), viewer.getDownsampleFactor(), null, viewer.getImageDisplay(), 250); g2d.dispose(); // Put pixels into an OpenCV image byte[] buffer = ((DataBufferByte) imgTemp.getRaster().getDataBuffer()).getData(); mat.put(0, 0, buffer); // Imgproc.cvtColor(mat, mat, Imgproc.COLOR_BGR2Lab); // blurSigma = 4; double blurSigma = Math.max(0.5, getWandSigmaPixels()); double size = Math.ceil(blurSigma * 2) * 2 + 1; blurSize.width = size; blurSize.height = size; // Smooth a little Imgproc.GaussianBlur(mat, mat, blurSize, blurSigma); // Imgproc.cvtColor(mat, mat, Imgproc.COLOR_RGB2Lab); MatOfDouble mean = new MatOfDouble(); MatOfDouble stddev = new MatOfDouble(); Core.meanStdDev(mat, mean, stddev); // logger.trace(stddev.dump()); double[] stddev2 = stddev.toArray(); double scale = .4; for (int i = 0; i < stddev2.length; i++) stddev2[i] = stddev2[i] * scale; threshold.set(stddev2); mean.release(); stddev.release(); matMask.setTo(zero); Imgproc.circle(matMask, seed, w / 2, one); Imgproc.floodFill(mat, matMask, seed, one, null, threshold, threshold, 4 | (2 << 8) | Imgproc.FLOODFILL_MASK_ONLY | Imgproc.FLOODFILL_FIXED_RANGE); Core.subtract(matMask, one, matMask); if (strel == null) strel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(5, 5)); Imgproc.morphologyEx(matMask, matMask, Imgproc.MORPH_CLOSE, strel); //// Imgproc.morphologyEx(matMask, matMask, Imgproc.MORPH_OPEN, Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, size)); // //// threshold = new Scalar(10, 10, 10); // double[] stddev2 = stddev.toArray(); // double scale = .5; // threshold = new Scalar(stddev2[0]*scale, stddev2[1]*scale, stddev2[2]*scale); contours.clear(); if (contourHierarchy == null) contourHierarchy = new Mat(); Imgproc.findContours(matMask, contours, contourHierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); // logger.trace("Contours: " + contours.size()); Path2D path = new Path2D.Float(); boolean isOpen = false; for (MatOfPoint contour : contours) { // Discard single pixels / lines if (contour.size().height <= 2) continue; // Create a polygon ROI boolean firstPoint = true; for (Point p : contour.toArray()) { double xx = (p.x - w / 2 - 1) * downsample + x; double yy = (p.y - w / 2 - 1) * downsample + y; if (firstPoint) { path.moveTo(xx, yy); firstPoint = false; isOpen = true; } else path.lineTo(xx, yy); } } if (isOpen) path.closePath(); long endTime = System.currentTimeMillis(); logger.trace(getClass().getSimpleName() + " time: " + (endTime - startTime)); if (pLast == null) pLast = new Point2D.Double(x, y); else pLast.setLocation(x, y); return path; }