List of usage examples for org.opencv.imgproc Imgproc threshold
public static double threshold(Mat src, Mat dst, double thresh, double maxval, int type)
From source file:de.hftl_projekt.ict.MainActivity.java
/** * method to reduce the color (quantize) the given matrix (image) * @param image input matrix/* w ww.ja v a 2 s . c o m*/ * @return modified input matrix */ public Mat reduceColors(Mat image) { if (channels.size() == 0) { for (int i = 0; i < image.channels(); i++) { Mat channel = new Mat(); // fill array with a matrix for each channel channels.add(channel); } } int i = 0; // process each channel individually for (Mat c : channels) { Core.extractChannel(image, c, i); // binary quantization (set threshold so each color (R, G, B) can have the value (0 or 255) ) // and using the Otsu algorithm to optimize the quantization Imgproc.threshold(c, c, 0, 255, Imgproc.THRESH_BINARY_INV + Imgproc.THRESH_OTSU); i++; } Core.merge(channels, image); // put the channel back together return image; }
From source file:detectiontest.ParticleDetector.java
/** * Particle detection algorithm./*from w w w. j av a2 s . c o m*/ * * @param image an image where we want to detect * @return list of detected particles */ public static List<Particle> detect(Mat image) { // blur the image to denoise Imgproc.blur(image, image, new Size(3, 3)); // thresholds the image Mat thresholded = new Mat(); Imgproc.threshold(image, thresholded, THRESHOLD, MAX, Imgproc.THRESH_TOZERO_INV); // detect contours List<MatOfPoint> contours = new ArrayList<>(); Imgproc.findContours(thresholded, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE, ORIGIN); // create particle from each contour List<Particle> particles = new ArrayList<>(); for (MatOfPoint contour : contours) { particles.add(new Particle(contour)); } return particles; }
From source file:edu.fiu.cate.breader.BaseSegmentation.java
/** * Finds the bounding box for the book on the stand using * the high resolution image.//from w w w . j a va2 s .co m * @param src- High Resolution image of the book * @return Rectangle delineating the book */ public Rect highRes(Mat src) { Mat dst = src.clone(); Imgproc.blur(src, dst, new Size(100.0, 100.0), new Point(-1, -1), Core.BORDER_REPLICATE); Imgproc.threshold(dst, dst, 0, 255, Imgproc.THRESH_BINARY_INV + Imgproc.THRESH_OTSU); Imgproc.Canny(dst, dst, 50, 200, 3, false); List<MatOfPoint> contours = new LinkedList<>(); Mat hierarchy = new Mat(); Imgproc.findContours(dst, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE, new Point(0, 0)); Mat color = new Mat(); Imgproc.cvtColor(src, color, Imgproc.COLOR_GRAY2BGR); for (int k = 0; k < contours.size(); k++) { byte[] vals = ITools.getHeatMapColor((float) k / (float) contours.size()); Imgproc.drawContours(color, contours, k, new Scalar(vals[0], vals[1], vals[2]), 8); } new IViewer("HighRes Contours ", BReaderTools.bufferedImageFromMat(color)); Point center = new Point(src.cols() / 2, src.rows() / 2); //Check hierarchy tree int[] res = polySearch(center, hierarchy, contours, 0); while (res[0] != 1 && res[2] != -1) { res = polySearch(center, hierarchy, contours, res[2]); if (res[0] == 1) break; } MatOfInt tHull = new MatOfInt(); int index = 0; if (res[1] != -1) { index = res[1]; } Imgproc.convexHull(contours.get(index), tHull); //get bounding box MatOfPoint cont = contours.get(index); Point[] points = new Point[tHull.rows()]; for (int i = 0; i < tHull.rows(); i++) { int pIndex = (int) tHull.get(i, 0)[0]; points[i] = new Point(cont.get(pIndex, 0)); } Rect out = Imgproc.boundingRect(new MatOfPoint(points)); return out; }
From source file:edu.ucue.tfc.Modelo.VideoProcessor.java
/** * Processes {@code firstFrame} and {@code secondFrame}. * @param firstFrame the first frame of a cycle. *///from w ww. j ava2 s . c o m private void processFrame(Mat firstFrame) { double contourArea = 0; int position = 0; try { /** * Redimensiona el el cuadro actual * */ Imgproc.resize(firstFrame, firstFrame, frameSize); /** * Convierte el cuadro por segundo a escala de grises */ Imgproc.cvtColor(firstFrame, firstGrayImage, Imgproc.COLOR_BGR2GRAY); /** * Lee el siguiente cuadro, lo redimensiona y convierte a escala de grises */ video.read(secondFrame); Imgproc.resize(secondFrame, secondFrame, frameSize); Imgproc.cvtColor(secondFrame, secondGrayImage, Imgproc.COLOR_BGR2GRAY); /** * Obtiene la diferencia absoluta por pixel de los cuadros anteriores. */ Core.absdiff(firstGrayImage, secondGrayImage, differenceOfImages); Imgproc.threshold(differenceOfImages, thresholdImage, 25, 255, Imgproc.THRESH_BINARY); Imgproc.blur(thresholdImage, thresholdImage, new Size(12, 12)); Imgproc.threshold(thresholdImage, thresholdImage, 20, 255, Imgproc.THRESH_BINARY); ///// for (int i = 0; i < contours.size(); ++i) { contours.get(i).release(); } contours.clear(); /** * La linea Horizontal */ Imgproc.line(firstFrame, controlPoints.get(6), controlPoints.get(7), new Scalar(255, 0, 0), Imgproc.LINE_4); Imgproc.findContours(thresholdImage, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE); for (int i = 0; i < hullPoints.size(); ++i) { hullPoints.get(i).release(); } hullPoints.clear(); for (int i = 0; i < contours.size(); i++) { MatOfInt tmp = new MatOfInt(); Imgproc.convexHull(contours.get(i), tmp, false); hullPoints.add(tmp); } /** * Busca el contorno con el rea ms grande */ if (contours.size() > 0) { for (int i = 0; i < contours.size(); i++) { if (Imgproc.contourArea(contours.get(i)) > contourArea) { contourArea = Imgproc.contourArea(contours.get(i)); position = i; boundingRectangle = Imgproc.boundingRect(contours.get(i)); } } } secondFrame.release(); hierarchy.release(); secondGrayImage.release(); firstGrayImage.release(); thresholdImage.release(); differenceOfImages.release(); } catch (Exception e) { System.out.println(e.getMessage()); } if (controlPoints.get(6).inside(boundingRectangle)) { Imgproc.line(frame, controlPoints.get(0), controlPoints.get(1), new Scalar(0, 0, 255), 2); wasAtLeftPoint = true; } else if (!controlPoints.get(6).inside(boundingRectangle)) { Imgproc.line(frame, controlPoints.get(0), controlPoints.get(1), new Scalar(0, 255, 0), 2); } if (controlPoints.get(8).inside(boundingRectangle)) { Imgproc.line(frame, controlPoints.get(2), controlPoints.get(3), new Scalar(0, 0, 255), 2); wasAtCenterPoint = true; } else if (!controlPoints.get(8).inside(boundingRectangle)) { Imgproc.line(frame, controlPoints.get(2), controlPoints.get(3), new Scalar(0, 255, 0), 2); } if (controlPoints.get(7).inside(boundingRectangle)) { Imgproc.line(frame, controlPoints.get(4), controlPoints.get(5), new Scalar(0, 0, 255), 2); wasAtRightPoint = true; } else if (!controlPoints.get(7).inside(boundingRectangle)) { Imgproc.line(frame, controlPoints.get(4), controlPoints.get(5), new Scalar(0, 255, 0), 2); } if (wasAtCenterPoint && wasAtLeftPoint && wasAtRightPoint) { detectedCarsCount++; wasDetected = true; wasAtCenterPoint = false; wasAtLeftPoint = false; wasAtRightPoint = false; } if (contourArea > 3000) { Imgproc.drawContours(frame, contours, position, new Scalar(255, 255, 255)); } }
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;// w w w . j av a 2s.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:finalpro.FinalPro.java
public static String threshholding() { Mat destination = null;/*from w w w .j a v a 2 s. c om*/ Mat source = null; String str = ""; try { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); source = Imgcodecs.imread("C:/QuadPotroler/FinalPro/src/images/20151207_153915.jpg", Imgcodecs.CV_LOAD_IMAGE_COLOR); destination = new Mat(source.rows(), source.cols(), source.type()); destination = source; Imgproc.threshold(source, destination, 127, 255, Imgproc.THRESH_TOZERO); Imgcodecs.imwrite("C:/QuadPotroler/FinalPro/src/images/threshdold.jpg", destination); str = "C:/QuadPotroler/FinalPro/src/images/threshdold.jpg"; } catch (Exception e) { System.out.println("error: " + e.getMessage()); } return str; }
From source file:fuzzycv.MainFrame.java
private Mat removeBG(Mat frame) { Mat hsvImg = new Mat(); List<Mat> hsvPlanes = new ArrayList<>(); Mat thresholdImg = new Mat(); //threshold the image with the histogram average value hsvImg.create(frame.size(), CvType.CV_8U); Imgproc.cvtColor(frame, hsvImg, Imgproc.COLOR_BGR2HSV); Core.split(hsvImg, hsvPlanes);// w w w . j a v a2 s. c om double threshValue = getHistoAvg(hsvImg, hsvPlanes.get(0)); if (inverseCheckBox.isSelected()) { Imgproc.threshold(hsvPlanes.get(0), thresholdImg, threshValue, 179.0, Imgproc.THRESH_BINARY_INV); } else { Imgproc.threshold(hsvPlanes.get(0), thresholdImg, threshValue, 179.0, Imgproc.THRESH_BINARY); } Imgproc.blur(thresholdImg, thresholdImg, new Size(5, 5)); // dilate to fill gaps, erode to smooth edges Imgproc.dilate(thresholdImg, thresholdImg, new Mat(), new Point(-1, 1), 6); Imgproc.erode(thresholdImg, thresholdImg, new Mat(), new Point(-1, 1), 6); Imgproc.threshold(thresholdImg, thresholdImg, threshValue, 179.0, Imgproc.THRESH_BINARY); // create the new image Mat foreground = new Mat(frame.size(), CvType.CV_8UC3, new Scalar(255, 255, 255)); frame.copyTo(foreground, thresholdImg); return foreground; }
From source file:gab.opencv.OpenCV.java
License:Open Source License
/** * Apply a global threshold to an image. Produces a binary image * with white pixels where the original image was above the threshold * and black where it was below.//from w w w. j a v a 2 s. c o m * * @param threshold * An int from 0-255. */ public void threshold(int threshold) { Imgproc.threshold(getCurrentMat(), getCurrentMat(), threshold, 255, Imgproc.THRESH_BINARY); }
From source file:gab.opencv.OpenCV.java
License:Open Source License
/** * Apply a global threshold to the image. The threshold is determined by Otsu's method, which * attempts to divide the image at a threshold which minimizes the variance of pixels in the black * and white regions.// www .j a va 2 s . c o m * * See: https://en.wikipedia.org/wiki/Otsu's_method */ public void threshold() { Imgproc.threshold(getCurrentMat(), getCurrentMat(), 0, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU); }
From source file:gab.opencv.OpenCVProcessingUtils.java
License:Open Source License
public void threshold(int threshold) { Imgproc.threshold(getCurrentMat(), getCurrentMat(), threshold, 255, Imgproc.THRESH_BINARY); }