Java Code Examples for org.opencv.imgproc.Imgproc#GaussianBlur
The following examples show how to use
org.opencv.imgproc.Imgproc#GaussianBlur .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OpenCVNonMavenExamples.java From Java-for-Data-Science with MIT License | 6 votes |
public void sharpenImage() { String fileName = "SharpnessExample2.png"; fileName = "smoothCat.jpg"; fileName = "blurredText.jpg"; fileName = "Blurred Text3.jpg"; try { // Not working that well !!! Mat source = Imgcodecs.imread(fileName, // Imgcodecs.CV_LOAD_IMAGE_COLOR); Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE); Mat destination = new Mat(source.rows(), source.cols(), source.type()); Imgproc.GaussianBlur(source, destination, new Size(0, 0), 10); // The following was used witht he cat // Core.addWeighted(source, 1.5, destination, -0.75, 0, destination); // Core.addWeighted(source, 2.5, destination, -1.5, 0, destination); Core.addWeighted(source, 1.5, destination, -0.75, 0, destination); Imgcodecs.imwrite("sharpenedCat.jpg", destination); } catch (Exception ex) { ex.printStackTrace(); } }
Example 2
Source File: TransmissionEstimate.java From OptimizedImageEnhance with MIT License | 6 votes |
public static Mat transEstimate(Mat img, int patchSz, double[] airlight, double lambda, double fTrans, int r, double eps, double gamma) { int rows = img.rows(); int cols = img.cols(); List<Mat> bgr = new ArrayList<>(); Core.split(img, bgr); int type = bgr.get(0).type(); // calculate the transmission map Mat T = computeTrans(img, patchSz, rows, cols, type, airlight, lambda, fTrans); // refine the transmission map img.convertTo(img, CvType.CV_8UC1); Mat gray = new Mat(); Imgproc.cvtColor(img, gray, Imgproc.COLOR_BGR2GRAY); gray.convertTo(gray, CvType.CV_32F); Core.divide(gray, new Scalar(255.0), gray); T = Filters.GuidedImageFilter(gray, T, r, eps); Mat Tsmooth = new Mat(); Imgproc.GaussianBlur(T, Tsmooth, new Size(81, 81), 40); Mat Tdetails = new Mat(); Core.subtract(T, Tsmooth, Tdetails); Core.multiply(Tdetails, new Scalar(gamma), Tdetails); Core.add(Tsmooth, Tdetails, T); return T; }
Example 3
Source File: HSVColorFilter.java From DogeCV with GNU General Public License v3.0 | 6 votes |
/** * Process a image and return a mask * @param input - Input image to process * @param mask - Output mask */ @Override public void process(Mat input, Mat mask) { // Copy the input to working mat workingMat = input.clone(); // Convert the input to HSV color space Imgproc.cvtColor(workingMat,workingMat,Imgproc.COLOR_RGB2HSV_FULL); // Blur the imgae Imgproc.GaussianBlur(workingMat,workingMat,new Size(5,5),0); // Run a inRange mask using the color and range Scalar lower = new Scalar(perfect.val[0] - (range.val[0]/2), perfect.val[1] - (range.val[1]/2),perfect.val[2] - (range.val[2]/2)); Scalar upper = new Scalar(perfect.val[0] + (range.val[0]/2), perfect.val[1] + (range.val[1]/2),perfect.val[2] + (range.val[2]/2)); Core.inRange(workingMat,lower,upper,mask); }
Example 4
Source File: MainActivity.java From OCR-Test with Apache License 2.0 | 6 votes |
public Bitmap convertToBlackWhite(Bitmap compressImage) { Log.d("CV", "Before converting to black"); Mat imageMat = new Mat(); Utils.bitmapToMat(compressImage, imageMat); Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_BGR2GRAY); Imgproc.GaussianBlur(imageMat, imageMat, new Size(3, 3), 0); //Imgproc.adaptiveThreshold(imageMat, imageMat, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV, 5, 4); //Imgproc.medianBlur(imageMat, imageMat, 3); Imgproc.threshold(imageMat, imageMat, 0, 255, Imgproc.THRESH_OTSU); Bitmap newBitmap = compressImage; Utils.matToBitmap(imageMat, newBitmap); imageView.setImageBitmap(newBitmap); Log.d("CV", "After converting to black"); return newBitmap; }
Example 5
Source File: MainActivity.java From MOAAP with MIT License | 6 votes |
@Override protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { //Put it there, just in case:) super.onActivityResult(requestCode, resultCode, imageReturnedIntent); switch(requestCode) { case SELECT_PHOTO: if(resultCode == RESULT_OK && read_external_storage_granted){ try { final Uri imageUri = imageReturnedIntent.getData(); final InputStream imageStream = getContentResolver().openInputStream(imageUri); final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream); src = new Mat(selectedImage.getHeight(), selectedImage.getWidth(), CvType.CV_8UC4); Utils.bitmapToMat(selectedImage, src); src_gray = new Mat(selectedImage.getHeight(), selectedImage.getWidth(), CvType.CV_8UC1); switch (ACTION_MODE) { case HomeActivity.GAUSSIAN_BLUR: Imgproc.GaussianBlur(src, src, new Size(9, 9), 0); break; case HomeActivity.MEAN_BLUR: Imgproc.blur(src, src, new Size(9, 9)); break; case HomeActivity.MEDIAN_BLUR: Imgproc.medianBlur(src, src, 9); break; case HomeActivity.SHARPEN: Mat kernel = new Mat(3, 3, CvType.CV_16SC1); //int[] values = {0, -1, 0, -1, 5, -1, 0, -1, 0}; Log.d("imageType", CvType.typeToString(src.type()) + ""); kernel.put(0, 0, 0, -1, 0, -1, 5, -1, 0, -1, 0); Imgproc.filter2D(src, src, src_gray.depth(), kernel); break; case HomeActivity.DILATE: Imgproc.cvtColor(src, src_gray, Imgproc.COLOR_BGR2GRAY); Imgproc.threshold(src_gray, src_gray, 100, 255, Imgproc.THRESH_BINARY); Mat kernelDilate = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(3, 3)); Imgproc.dilate(src_gray, src_gray, kernelDilate); Imgproc.cvtColor(src_gray, src, Imgproc.COLOR_GRAY2RGBA, 4); break; case HomeActivity.ERODE: Imgproc.cvtColor(src, src_gray, Imgproc.COLOR_BGR2GRAY); Imgproc.threshold(src_gray, src_gray, 100, 255, Imgproc.THRESH_BINARY); Mat kernelErode = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(5, 5)); Imgproc.erode(src_gray, src_gray, kernelErode); Imgproc.cvtColor(src_gray, src, Imgproc.COLOR_GRAY2RGBA, 4); break; case HomeActivity.THRESHOLD: Imgproc.cvtColor(src, src_gray, Imgproc.COLOR_BGR2GRAY); Imgproc.threshold(src_gray, src_gray, 100, 255, Imgproc.THRESH_BINARY); Imgproc.cvtColor(src_gray, src, Imgproc.COLOR_GRAY2RGBA, 4); break; case HomeActivity.ADAPTIVE_THRESHOLD: Imgproc.cvtColor(src, src_gray, Imgproc.COLOR_BGR2GRAY); Imgproc.adaptiveThreshold(src_gray, src_gray, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 3, 0); Imgproc.cvtColor(src_gray, src, Imgproc.COLOR_GRAY2RGBA, 4); break; } Bitmap processedImage = Bitmap.createBitmap(src.cols(), src.rows(), Bitmap.Config.ARGB_8888); Log.i("imageType", CvType.typeToString(src.type()) + ""); Utils.matToBitmap(src, processedImage); ivImage.setImageBitmap(selectedImage); ivImageProcessed.setImageBitmap(processedImage); Log.i("process", "process done"); } catch (FileNotFoundException e) { e.printStackTrace(); } } break; } }
Example 6
Source File: OpenCVoperation.java From Human-hair-detection with Apache License 2.0 | 6 votes |
public void skinSegmentation() { matrix3_skindetection = new Mat(matrix2_grabcut.size(),matrix2_grabcut.type()); matrix3_skindetection.setTo(new Scalar(0,0,255)); Mat skinMask = new Mat(); Mat hsvMatrix = new Mat(); Scalar lower = new Scalar(0,48,80); Scalar upper = new Scalar(20,255,255); Imgproc.cvtColor(matrix2_grabcut, hsvMatrix, Imgproc.COLOR_BGR2HSV); Core.inRange(hsvMatrix, lower, upper, skinMask); Mat kernel =Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE,new Size(11,11)); Imgproc.erode(skinMask, skinMask, kernel); Imgproc.dilate(skinMask, skinMask, kernel); Imgproc.GaussianBlur(skinMask,skinMask, new Size(3,3), 0); Core.bitwise_and(matrix2_grabcut, matrix2_grabcut, matrix3_skindetection,skinMask); Imgcodecs.imwrite(resultDirectory+skinDetectionOutput , matrix3_skindetection); }
Example 7
Source File: CVProcessor.java From CVScanner with GNU General Public License v3.0 | 5 votes |
public static Rect detectBorder(Mat original){ Mat src = original.clone(); Log.d(TAG, "1 original: " + src.toString()); Imgproc.GaussianBlur(src, src, new Size(3, 3), 0); Log.d(TAG, "2.1 --> Gaussian blur done\n blur: " + src.toString()); Imgproc.cvtColor(src, src, Imgproc.COLOR_RGBA2GRAY); Log.d(TAG, "2.2 --> Grayscaling done\n gray: " + src.toString()); Mat sobelX = new Mat(); Mat sobelY = new Mat(); Imgproc.Sobel(src, sobelX, CvType.CV_32FC1, 2, 0, 5, 1, 0); Log.d(TAG, "3.1 --> Sobel done.\n X: " + sobelX.toString()); Imgproc.Sobel(src, sobelY, CvType.CV_32FC1, 0, 2, 5, 1, 0); Log.d(TAG, "3.2 --> Sobel done.\n Y: " + sobelY.toString()); Mat sum_img = new Mat(); Core.addWeighted(sobelX, 0.5, sobelY, 0.5, 0.5, sum_img); //Core.add(sobelX, sobelY, sum_img); Log.d(TAG, "4 --> Addition done. sum: " + sum_img.toString()); sobelX.release(); sobelY.release(); Mat gray = new Mat(); Core.normalize(sum_img, gray, 0, 255, Core.NORM_MINMAX, CvType.CV_8UC1); Log.d(TAG, "5 --> Normalization done. gray: " + gray.toString()); sum_img.release(); Mat row_proj = new Mat(); Mat col_proj = new Mat(); Core.reduce(gray, row_proj, 1, Core.REDUCE_AVG, CvType.CV_8UC1); Log.d(TAG, "6.1 --> Reduce done. row: " + row_proj.toString()); Core.reduce(gray, col_proj, 0, Core.REDUCE_AVG, CvType.CV_8UC1); Log.d(TAG, "6.2 --> Reduce done. col: " + col_proj.toString()); gray.release(); Imgproc.Sobel(row_proj, row_proj, CvType.CV_8UC1, 0, 2); Log.d(TAG, "7.1 --> Sobel done. row: " + row_proj.toString()); Imgproc.Sobel(col_proj, col_proj, CvType.CV_8UC1, 2, 0); Log.d(TAG, "7.2 --> Sobel done. col: " + col_proj.toString()); Rect result = new Rect(); int half_pos = (int) (row_proj.total()/2); Mat row_sub = new Mat(row_proj, new Range(0, half_pos), new Range(0, 1)); Log.d(TAG, "8.1 --> Copy sub matrix done. row: " + row_sub.toString()); result.y = (int) Core.minMaxLoc(row_sub).maxLoc.y; Log.d(TAG, "8.2 --> Minmax done. Y: " + result.y); row_sub.release(); Mat row_sub2 = new Mat(row_proj, new Range(half_pos, (int) row_proj.total()), new Range(0, 1)); Log.d(TAG, "8.3 --> Copy sub matrix done. row: " + row_sub2.toString()); result.height = (int) (Core.minMaxLoc(row_sub2).maxLoc.y + half_pos - result.y); Log.d(TAG, "8.4 --> Minmax done. Height: " + result.height); row_sub2.release(); half_pos = (int) (col_proj.total()/2); Mat col_sub = new Mat(col_proj, new Range(0, 1), new Range(0, half_pos)); Log.d(TAG, "9.1 --> Copy sub matrix done. col: " + col_sub.toString()); result.x = (int) Core.minMaxLoc(col_sub).maxLoc.x; Log.d(TAG, "9.2 --> Minmax done. X: " + result.x); col_sub.release(); Mat col_sub2 = new Mat(col_proj, new Range(0, 1), new Range(half_pos, (int) col_proj.total())); Log.d(TAG, "9.3 --> Copy sub matrix done. col: " + col_sub2.toString()); result.width = (int) (Core.minMaxLoc(col_sub2).maxLoc.x + half_pos - result.x); Log.d(TAG, "9.4 --> Minmax done. Width: " + result.width); col_sub2.release(); row_proj.release(); col_proj.release(); src.release(); return result; }
Example 8
Source File: FeatureWeight.java From OptimizedImageEnhance with MIT License | 5 votes |
public static Mat Saliency(Mat img) { // blur image with a 3x3 or 5x5 Gaussian filter Mat gfbgr = new Mat(); Imgproc.GaussianBlur(img, gfbgr, new Size(3, 3), 3); // Perform sRGB to CIE Lab color space conversion Mat LabIm = new Mat(); Imgproc.cvtColor(gfbgr, LabIm, Imgproc.COLOR_BGR2Lab); // Compute Lab average values (note that in the paper this average is found from the // un-blurred original image, but the results are quite similar) List<Mat> lab = new ArrayList<>(); Core.split(LabIm, lab); Mat l = lab.get(0); l.convertTo(l, CvType.CV_32F); Mat a = lab.get(1); a.convertTo(a, CvType.CV_32F); Mat b = lab.get(2); b.convertTo(b, CvType.CV_32F); double lm = Core.mean(l).val[0]; double am = Core.mean(a).val[0]; double bm = Core.mean(b).val[0]; // Finally compute the saliency map Mat sm = Mat.zeros(l.rows(), l.cols(), l.type()); Core.subtract(l, new Scalar(lm), l); Core.subtract(a, new Scalar(am), a); Core.subtract(b, new Scalar(bm), b); Core.add(sm, l.mul(l), sm); Core.add(sm, a.mul(a), sm); Core.add(sm, b.mul(b), sm); return sm; }
Example 9
Source File: WeightCalculate.java From ImageEnhanceViaFusion with MIT License | 5 votes |
public static Mat Saliency(Mat img) { // blur image with a 3x3 or 5x5 Gaussian filter Mat gfbgr = new Mat(); Imgproc.GaussianBlur(img, gfbgr, new Size(3, 3), 3); // Perform sRGB to CIE Lab color space conversion Mat LabIm = new Mat(); Imgproc.cvtColor(gfbgr, LabIm, Imgproc.COLOR_BGR2Lab); // Compute Lab average values (note that in the paper this average is found from the // un-blurred original image, but the results are quite similar) List<Mat> lab = new ArrayList<Mat>(); Core.split(LabIm, lab); Mat l = lab.get(0); l.convertTo(l, CvType.CV_32F); Mat a = lab.get(1); a.convertTo(a, CvType.CV_32F); Mat b = lab.get(2); b.convertTo(b, CvType.CV_32F); double lm = Core.mean(l).val[0]; double am = Core.mean(a).val[0]; double bm = Core.mean(b).val[0]; // Finally compute the saliency map Mat sm = Mat.zeros(l.rows(), l.cols(), l.type()); Core.subtract(l, new Scalar(lm), l); Core.subtract(a, new Scalar(am), a); Core.subtract(b, new Scalar(bm), b); Core.add(sm, l.mul(l), sm); Core.add(sm, a.mul(a), sm); Core.add(sm, b.mul(b), sm); return sm; }
Example 10
Source File: DifferenceOfGaussian.java From Android-Face-Recognition-with-Deep-Learning-Library with Apache License 2.0 | 5 votes |
public PreProcessor preprocessImage(PreProcessor preProcessor) { List<Mat> images = preProcessor.getImages(); List<Mat> processed = new ArrayList<Mat>(); for (Mat img : images){ Mat gauss1 = new Mat(); Mat gauss2 = new Mat(); Imgproc.GaussianBlur(img, gauss1, size1, sigma1); Imgproc.GaussianBlur(img, gauss2, size2, sigma2); Core.absdiff(gauss1, gauss2, img); processed.add(img); } preProcessor.setImages(processed); return preProcessor; }
Example 11
Source File: CbColorFilter.java From DogeCV with GNU General Public License v3.0 | 5 votes |
@Override public void process(Mat input, Mat mask) { Imgproc.cvtColor(input, input, Imgproc.COLOR_RGB2YCrCb); // Blur it Imgproc.GaussianBlur(input,input,new Size(5,5),0); // Run in range check Core.inRange(input, lower, upper, mask); input.release(); }
Example 12
Source File: HSVRangeFilter.java From DogeCV with GNU General Public License v3.0 | 5 votes |
/** * Process a image and return a mask * @param input - Input image to process * @param mask - Output mask */ @Override public void process(Mat input, Mat mask) { // Convert the input to HSV Imgproc.cvtColor(input,input,Imgproc.COLOR_RGB2HSV_FULL); // Blur it Imgproc.GaussianBlur(input,input,new Size(5,5),0); // Run in range check Core.inRange(input,lower,upper,mask); input.release(); }
Example 13
Source File: PatchGenerator.java From OpenTLDAndroid with Apache License 2.0 | 5 votes |
/** * * @param image * @param T * @param patch OUTPUT * @param patchSize */ void generate(final Mat image, final Mat T, Mat patch, Size patchSize, final RNG rng){ patch.create( patchSize, image.type() ); if( backgroundMin != backgroundMax ) { Core.randu(patch, backgroundMin, backgroundMax); // TODO if that null scalar OK or should it be new Scalar(0) ? Imgproc.warpAffine(image, patch, T, patchSize, Imgproc.INTER_LINEAR, Imgproc.BORDER_TRANSPARENT, null); } else { Imgproc.warpAffine(image, patch, T, patchSize, Imgproc.INTER_LINEAR, Imgproc.BORDER_CONSTANT, new Scalar(backgroundMin)); } int ksize = randomBlur ? rng.nextInt() % 9 - 5 : 0; if( ksize > 0 ) { ksize = ksize * 2 + 1; Imgproc.GaussianBlur(patch, patch, new Size(ksize, ksize), 0, 0); } if( noiseRange > 0 ) { final Mat noise = new Mat(patchSize, image.type()); int delta = (image.depth() == CvType.CV_8U ? 128 : (image.depth() == CvType.CV_16U ? 32768 : 0)); Core.randn(noise, delta, noiseRange); // TODO this was different !! Core.addWeighted(patch, 1, noise, 1, -delta, patch); // if( backgroundMin != backgroundMax ) // addWeighted(patch, 1, noise, 1, -delta, patch); // else // { // for( int i = 0; i < patchSize.height; i++ ) // { // uchar* prow = patch.ptr<uchar>(i); // const uchar* nrow = noise.ptr<uchar>(i); // for( int j = 0; j < patchSize.width; j++ ) // if( prow[j] != backgroundMin ) // prow[j] = saturate_cast<uchar>(prow[j] + nrow[j] - delta); // } // } } }
Example 14
Source File: CVProcessor.java From CVScanner with GNU General Public License v3.0 | 5 votes |
public static Mat sharpenImage(Mat src){ Mat sharped = new Mat(); Imgproc.GaussianBlur(src, sharped, new Size(0, 0), 3); Core.addWeighted(src, 1.5, sharped, -0.5, 0, sharped); return sharped; }
Example 15
Source File: Blur.java From go-bees with GNU General Public License v3.0 | 5 votes |
@Override public Mat process(@NonNull Mat frame) { if (frame.empty()) { Log.e("Invalid input frame."); return null; } Mat tmp = frame.clone(); // Apply gaussian blur for (int i = 0; i < REPETITIONS; i++) { Imgproc.GaussianBlur(tmp, tmp, new Size(KERNEL_SIZE, KERNEL_SIZE), 0); } return tmp; }
Example 16
Source File: Tld.java From OpenTLDAndroid with Apache License 2.0 | 4 votes |
/** * Structure the classifier into 3 stages: * a) patch variance * b) ensemble of ferns classifier * c) nearest neighbour */ private Pair<List<DetectionStruct>, List<DetectionStruct>> detect(final Mat frame){ Log.i(Util.TAG, "[DETECT]"); final List<DetectionStruct> fernClassDetected = new ArrayList<Tld.DetectionStruct>(); //dt final List<DetectionStruct> nnMatches = new ArrayList<Tld.DetectionStruct>(); //dbb // 0. Cleaning _boxClusterMap.clear(); // 1. DETECTION final Mat img = new Mat(frame.rows(), frame.cols(), CvType.CV_8U); updateIntegralImgs(frame); Imgproc.GaussianBlur(frame, img, new Size(9, 9), 1.5); // Apply the Variance filter TODO : Bottleneck int a=0; for(BoundingBox box : _grid){ // a) speed up by doing the features/ferns check ONLY if the variance is high enough ! if(Util.getVar(box, _iisumJava, _iisqsumJava, _iiCols) >= _var ){ a++; final Mat patch = img.submat(box); final int[] allFernsHashCodes = _classifierFern.getAllFernsHashCodes(patch, box.scaleIdx); final double averagePosterior = _classifierFern.averagePosterior(allFernsHashCodes); _fernDetectionNegDataForLearning.put(box, allFernsHashCodes);// store for later use in learning // b) if(averagePosterior > _classifierFern.getFernPosThreshold()){ fernClassDetected.add(new DetectionStruct(box, allFernsHashCodes, averagePosterior, patch)); } } } Log.i(Util.TAG, a + " Bounding boxes passed the variance filter (" + _var + ")"); Log.i(Util.TAG, fernClassDetected.size() + " Initial detected from Fern Classifier"); if(fernClassDetected.size() == 0){ Log.i(Util.TAG, "[DETECT END]"); return null; } // keep only the best Util.keepBestN(fernClassDetected, MAX_DETECTED, new Comparator<DetectionStruct>() { @Override public int compare(DetectionStruct detS1, DetectionStruct detS2) { return Double.compare(detS1.averagePosterior, detS2.averagePosterior); } }); // 2. MATCHING using the NN classifier c) for(DetectionStruct detStruct : fernClassDetected){ // update detStruct.patch to params.patch_size and normalise it Mat pattern = new Mat(); resizeZeroMeanStdev(detStruct.patch, pattern, _params.patch_size); detStruct.nnConf = _classifierNN.nnConf(pattern); Log.i(Util.TAG, "NNConf: " + detStruct.nnConf.relativeSimilarity + " / " + detStruct.nnConf.conservativeSimilarity + " Threshold: " + _classifierNN.getNNThreshold()); // only keep valid boxes if(detStruct.nnConf.relativeSimilarity > _classifierNN.getNNThreshold()){ nnMatches.add(detStruct); } } Log.i(Util.TAG, "[DETECT END]"); return new Pair<List<DetectionStruct>, List<DetectionStruct>>(fernClassDetected, nnMatches); }
Example 17
Source File: Proc.java From android-object-distance with Apache License 2.0 | 4 votes |
public static double findMarkerWidth(String imgPath){ Mat frame = Highgui.imread(imgPath); Mat gscale = new Mat(); Mat blur = new Mat(); Mat edged = new Mat(); // convert the image to grayscale, blur it, and detect edges if(frame.channels()>1) Imgproc.cvtColor(frame, gscale, Imgproc.COLOR_BGR2GRAY); else gscale = frame; Imgproc.GaussianBlur(gscale, blur, new Size(5, 5), 0); Imgproc.Canny(blur, edged, 35, 125); // find the contours in the edged image and keep the largest one; // we'll assume that this is our piece of paper in the image List<MatOfPoint> contours = new ArrayList<>(); Mat hierarchy = new Mat(edged.width(), edged.height(), CvType.CV_8UC1); Imgproc.findContours(edged.clone(), contours, hierarchy, Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE); int max_idx = 0; // if any contour exist... if (hierarchy.size().height > 0 && hierarchy.size().width > 0) { double max_area = 0; double area; // find the contour with largest area for (int idx = 0; idx >= 0; idx = (int) hierarchy.get(0, idx)[0]) { area = Imgproc.contourArea(contours.get(idx)); if(area > max_area){ max_area = area; max_idx = idx; } Imgproc.drawContours(frame, contours, idx, new Scalar(0, 0, 255)); } //Riz: Save File //Imgproc.drawContours(frame, contours, max_idx, new Scalar(250, 0, 0)); byte[] bytes = new byte[ frame.rows() * frame.cols() * frame.channels() ]; File file = new File(CameraActivity.activity.getExternalFilesDir(null), "pic_contour"+ Integer.toString(pic_count) + ".jpg"); pic_count++; Boolean bool = null; String filename = file.toString(); bool = Highgui.imwrite(filename, frame); if (bool == true) Log.d(LOG_TAG, "SUCCESS writing image to external storage"); else Log.d(LOG_TAG, "Fail writing image to external storage"); Log.i(LOG_TAG, "Max Area: " + Double.toString(max_area)); } else{ Log.e(LOG_TAG, "No Contour Found!"); } MatOfPoint2f newPoint = new MatOfPoint2f(contours.get(max_idx).toArray()); return Imgproc.arcLength(newPoint, true); }
Example 18
Source File: LeviColorFilter.java From DogeCV with GNU General Public License v3.0 | 4 votes |
/** * Process a image and return a mask * @param input - Input image to process * @param mask - Output mask */ @Override public void process(Mat input, Mat mask) { channels = new ArrayList<>(); switch(color){ case RED: if(threshold == -1){ threshold = 164; } Imgproc.cvtColor(input, input, Imgproc.COLOR_RGB2Lab); Imgproc.GaussianBlur(input,input,new Size(3,3),0); Core.split(input, channels); Imgproc.threshold(channels.get(1), mask, threshold, 255, Imgproc.THRESH_BINARY); break; case BLUE: if(threshold == -1){ threshold = 145; } Imgproc.cvtColor(input, input, Imgproc.COLOR_RGB2YUV); Imgproc.GaussianBlur(input,input,new Size(3,3),0); Core.split(input, channels); Imgproc.threshold(channels.get(1), mask, threshold, 255, Imgproc.THRESH_BINARY); break; case WHITE: if(threshold == -1) { threshold = 150; } Imgproc.cvtColor(input, input, Imgproc.COLOR_RGB2Lab); Imgproc.GaussianBlur(input,input,new Size(3,3),0); Core.split(input, channels); Core.inRange(channels.get(0), new Scalar(threshold, 150, 40), new Scalar(255, 150, 150), mask); break; case YELLOW: if(threshold == -1){ threshold = 70; } Mat lab = new Mat(input.size(), 0); Imgproc.cvtColor(input, lab, Imgproc.COLOR_RGB2Lab); Mat temp = new Mat(); Core.inRange(input, new Scalar(0,0,0), new Scalar(255,255,164), temp); Mat mask2 = new Mat(input.size(), 0); temp.copyTo(mask2); input.copyTo(input, mask2); mask2.release(); temp.release(); lab.release(); Imgproc.cvtColor(input, input, Imgproc.COLOR_RGB2YUV); Imgproc.GaussianBlur(input,input,new Size(3,3),0); Core.split(input, channels); if(channels.size() > 0){ Imgproc.threshold(channels.get(1), mask, threshold, 255, Imgproc.THRESH_BINARY_INV); } break; } for(int i=0;i<channels.size();i++){ channels.get(i).release(); } input.release(); }
Example 19
Source File: CropImage.java From reader with MIT License | 4 votes |
private void makeDefault() { HighlightView hv = new HighlightView(mImageView); int width = mBitmap.getWidth(); int height = mBitmap.getHeight(); Rect imageRect = new Rect(0, 0, width, height); // make the default size about 4/5 of the width or height // int cropWidth = Math.min(width, height) * 4 / 5; // int cropHeight = cropWidth; int cropWidth = width; int cropHeight = height; if (mAspectX != 0 && mAspectY != 0) { if (mAspectX > mAspectY) { // �����辩缉��� cropHeight = cropWidth * mAspectY ;// mAspectX; } else { cropWidth = cropHeight * mAspectX ;// mAspectY; } } int x = (width - cropWidth) / 2; int y = (height - cropHeight) / 2; Mat imgSource = new Mat(); Utils.bitmapToMat(mBitmap, imgSource); //convert the image to black and white Imgproc.cvtColor(imgSource, imgSource, Imgproc.COLOR_BGR2GRAY); //convert the image to black and white does (8 bit) Imgproc.Canny(imgSource, imgSource, 50, 50); //apply gaussian blur to smoothen lines of dots Imgproc.GaussianBlur(imgSource, imgSource, new org.opencv.core.Size(5, 5), 5); //find the contours List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Imgproc.findContours(imgSource, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE); double maxArea = -1; int maxAreaIdx = -1; Log.d("size",Integer.toString(contours.size())); MatOfPoint temp_contour = contours.get(0); //the largest is at the index 0 for starting point MatOfPoint2f approxCurve = new MatOfPoint2f(); MatOfPoint largest_contour = contours.get(0); //largest_contour.ge List<MatOfPoint> largest_contours = new ArrayList<MatOfPoint>(); //Imgproc.drawContours(imgSource,contours, -1, new Scalar(0, 255, 0), 1); for (int idx = 0; idx < contours.size(); idx++) { temp_contour = contours.get(idx); double contourarea = Imgproc.contourArea(temp_contour); //compare this contour to the previous largest contour found if (contourarea > maxArea) { //check if this contour is a square MatOfPoint2f new_mat = new MatOfPoint2f( temp_contour.toArray() ); int contourSize = (int)temp_contour.total(); MatOfPoint2f approxCurve_temp = new MatOfPoint2f(); Imgproc.approxPolyDP(new_mat, approxCurve_temp, contourSize*0.05, true); if (approxCurve_temp.total() == 4) { maxArea = contourarea; maxAreaIdx = idx; approxCurve=approxCurve_temp; largest_contour = temp_contour; } } } Imgproc.cvtColor(imgSource, imgSource, Imgproc.COLOR_BayerBG2RGB); double[] temp_double; float x1, y1, x2, y2; temp_double = approxCurve.get(0,0); Point p1 = new Point(temp_double[0], temp_double[1]); x1 = (float)temp_double[0]; y1 = (float)temp_double[1]; //Core.circle(imgSource,p1,55,new Scalar(0,0,255)); //Imgproc.warpAffine(sourceImage, dummy, rotImage,sourceImage.size()); temp_double = approxCurve.get(1,0); Point p2 = new Point(temp_double[0], temp_double[1]); // Core.circle(imgSource,p2,150,new Scalar(255,255,255)); temp_double = approxCurve.get(2,0); Point p3 = new Point(temp_double[0], temp_double[1]); x2 = (float)temp_double[0]; y2 = (float)temp_double[1]; //Core.circle(imgSource,p3,200,new Scalar(255,0,0)); temp_double = approxCurve.get(3,0); Point p4 = new Point(temp_double[0], temp_double[1]); RectF cropRect = new RectF(x, y, x + cropWidth, y + cropHeight); //RectF cropRect = new RectF(x1, y1, x2, y2); // �����辩缉��� hv.setup(mImageMatrix, imageRect, cropRect, mCircleCrop,false /*mAspectX != 0 && mAspectY != 0*/); mImageView.add(hv); }
Example 20
Source File: Filter.java From FTCVision with MIT License | 2 votes |
/** * Blur the image using a Gaussian blur * * @param img Image matrix * @param amount Amount >= 0 */ public static void blur(Mat img, int amount) { Imgproc.GaussianBlur(img, img, new Size(2 * amount + 1, 2 * amount + 1), 0, 0); }