List of usage examples for org.opencv.core Mat clone
public Mat clone()
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 w w w. j a v 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.ObjectFinder.java
public String find(Mat input) { inputFrame = input.clone(); backprojectObjectHistogram();//from www.j av a2 s . c o m computeThresholdedBackProjection(); applyMorphologicalFilters(); computeSearchWindow(); computeTrackBox(); String path = ""; if (firstContour != null) { Point[] points = firstContour.toArray(); path = "M " + (int) points[0].x + " " + (int) points[0].y + " "; for (int i = 1; i < points.length; ++i) { Point point = points[i]; path += "L " + (int) point.x + " " + (int) point.y + " "; } path += "Z"; } return path; }
From source file:classes.ObjectFinder.java
public void find(Mat input, Mat output) { inputFrame = input.clone(); backprojectObjectHistogram();/*w ww. java 2s. c o m*/ computeThresholdedBackProjection(); applyMorphologicalFilters(); computeSearchWindow(); computeTrackBox(); drawOutput(output); }
From source file:classes.TextRecognitionPreparer.java
public static ArrayList<String> generateRecognizableImagesNames(Mat img, Scalar userPickedColor, String imageID, HttpServletRequest request) {//from www. j a v a 2 s . c o m ArrayList<String> imageNames = new ArrayList<String>(); Mat filledImage = img.clone(); Scalar newVal = new Scalar(userPickedColor.val[2], userPickedColor.val[1], userPickedColor.val[0]); Imgproc.floodFill(filledImage, new Mat(), new Point(0, 0), newVal); String file1 = imageID + "_filledImage.png"; // Highgui.imwrite(file1, filledImage); imageNames.add(ImageUtils.saveImage(filledImage, file1, request)); Mat filledGrayImage = new Mat(); Imgproc.cvtColor(filledImage, filledGrayImage, Imgproc.COLOR_BGR2GRAY); String file2 = imageID + "_filledGrayImage.png"; // Highgui.imwrite(file2, filledGrayImage); imageNames.add(ImageUtils.saveImage(filledGrayImage, file2, request)); Mat gaussianGrayImage = new Mat(); Imgproc.GaussianBlur(filledGrayImage, gaussianGrayImage, new Size(0, 0), 3); Core.addWeighted(filledGrayImage, 3.5, gaussianGrayImage, -1, 0, gaussianGrayImage); String file3 = imageID + "_sharpenedImage.png"; // Highgui.imwrite(file3, gaussianGrayImage); imageNames.add(ImageUtils.saveImage(gaussianGrayImage, file3, request)); // Mat filledBinarizedImage2 = new Mat(); // Imgproc.adaptiveThreshold(filledGrayImage, filledBinarizedImage2, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 75, 10); // String file5 = imageID + "_filledBinarizedImage2.png"; //// Highgui.imwrite(file11, filledBinarizedImage2); // imageNames.add(ImageUtils.saveImage(filledBinarizedImage2, file5)); // // Mat filledBinarizedImage1 = new Mat(); // Imgproc.adaptiveThreshold(filledGrayImage, filledBinarizedImage1, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 15, 4); // String file4 = imageID + "_filledBinarizedImage1.png"; //// Highgui.imwrite(file4, filledBinarizedImage1); // imageNames.add(ImageUtils.saveImage(filledBinarizedImage1, file4)); return imageNames; }
From source file:classes.TextRecognitionPreparer.java
public static ArrayList<BufferedImage> generateRecognizableBufferedImages(Mat img, Scalar backgroundColor, Scalar userPickedColor) {/*w w w . j a v a2 s .com*/ ArrayList<BufferedImage> images = new ArrayList<BufferedImage>(); Mat filledImage = img.clone(); Scalar newVal = new Scalar(userPickedColor.val[2], userPickedColor.val[1], userPickedColor.val[0]); Imgproc.floodFill(filledImage, new Mat(), new Point(0, 0), newVal); images.add(Util.mat2Img(filledImage)); Mat filledGrayImage = new Mat(); Imgproc.cvtColor(filledImage, filledGrayImage, Imgproc.COLOR_BGR2GRAY); images.add(Util.mat2Img(filledGrayImage)); Mat gaussianGrayImage = new Mat(); Imgproc.GaussianBlur(filledGrayImage, gaussianGrayImage, new Size(0, 0), 3); Core.addWeighted(filledGrayImage, 3.5, gaussianGrayImage, -1, 0, gaussianGrayImage); images.add(Util.mat2Img(gaussianGrayImage)); Mat filledBinarizedImage2 = new Mat(); Imgproc.adaptiveThreshold(filledGrayImage, filledBinarizedImage2, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 75, 10); images.add(Util.mat2Img(filledBinarizedImage2)); Mat filledBinarizedImage1 = new Mat(); Imgproc.adaptiveThreshold(filledGrayImage, filledBinarizedImage1, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 15, 4); images.add(Util.mat2Img(filledBinarizedImage1)); return images; }
From source file:classes.TextRecognitionPreparer.java
public static ArrayList<Mat> generateRecognizableImages(Mat img, Scalar backgroundColor, Scalar userPickedColor) {//from w w w . j a v a 2 s . c om ArrayList<Mat> images = new ArrayList<Mat>(); Mat filledImage = img.clone(); Scalar newVal = new Scalar(userPickedColor.val[2], userPickedColor.val[1], userPickedColor.val[0]); Imgproc.floodFill(filledImage, new Mat(), new Point(0, 0), newVal); String file1 = "filledImage.png"; // Highgui.imwrite(file1, filledImage); images.add(filledImage); Mat filledGrayImage = new Mat(); Imgproc.cvtColor(filledImage, filledGrayImage, Imgproc.COLOR_BGR2GRAY); String file2 = "filledGrayImage.png"; // Highgui.imwrite(file2, filledGrayImage); images.add(filledGrayImage); Mat gaussianGrayImage = new Mat(); Imgproc.GaussianBlur(filledGrayImage, gaussianGrayImage, new Size(0, 0), 3); Core.addWeighted(filledGrayImage, 3.5, gaussianGrayImage, -1, 0, gaussianGrayImage); // Core.addWeighted(filledGrayImage, 2.5, gaussianGrayImage, -0.5, 0, gaussianGrayImage); String file3 = "sharpenedImage.png"; // Highgui.imwrite(file3, gaussianGrayImage); images.add(gaussianGrayImage); Mat filledBinarizedImage = new Mat(); Imgproc.adaptiveThreshold(filledGrayImage, filledBinarizedImage, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 15, 4); String file4 = "filledBinarizedImage.png"; // Highgui.imwrite(file4, filledBinarizedImage); images.add(filledBinarizedImage); // BackgroundSubtractorMOG2 backgroundSubtractorMOG2 = new BackgroundSubtractorMOG2(); // Mat foregroundMask = new Mat(); // backgroundSubtractorMOG2.apply(img, foregroundMask); // Highgui.imwrite("mFGMask.png", foregroundMask); Scalar fillingColor = cluster(userPickedColor, img, 3); Mat replacedColor = replaceColor(img, backgroundColor, fillingColor); String file5 = "replacedColor.png"; // Highgui.imwrite(file5, replacedColor); images.add(replacedColor); Mat grayImage = new Mat(); Imgproc.cvtColor(replacedColor, grayImage, Imgproc.COLOR_BGR2GRAY); String file6 = "grayImage.png"; // Highgui.imwrite(file6, grayImage); images.add(grayImage); Mat binarized = new Mat(); Imgproc.adaptiveThreshold(grayImage, binarized, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 15, 4); String file7 = "binarized.png"; // Highgui.imwrite(file7, binarized); images.add(binarized); Mat colorReplacedEqualized = equalizeIntensity(replacedColor); String file8 = "colorReplacedEqualized.png"; // Highgui.imwrite(file8, colorReplacedEqualized); images.add(colorReplacedEqualized); Mat colorReducedImage = reduceColor(replacedColor, 64); String file9 = "replacedColorColorReduced.png"; // Highgui.imwrite(file9, colorReducedImage); images.add(colorReducedImage); // Equalizing image Mat colorReducedEqualized = equalizeIntensity(colorReducedImage); String file10 = "colorReducedEqualized.png"; // Highgui.imwrite(file10, colorReducedEqualized); images.add(colorReducedEqualized); return images; }
From source file:classes.TextRecognitionPreparer.java
static Mat replaceColor(Mat image, Scalar color1, Scalar color2) { Mat replaced = image.clone(); for (int y = 0; y < image.rows(); y++) { for (int x = 0; x < image.cols(); x++) { double[] values = image.get(y, x); double r = values[0]; double g = values[1]; double b = values[2]; if (b == color1.val[0] && g == color1.val[1] && r == color1.val[2]) { values[0] = color2.val[2]; values[1] = color2.val[1]; values[2] = color2.val[0]; }/*from w ww.j a v a 2s. c om*/ replaced.put(y, x, values); } } return replaced; }
From source file:cn.xiongyihui.webcam.setup.java
License:Open Source License
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setup); this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); final Button cameraButton = (Button) findViewById(R.id.cameraButton); final Button selectButton = (Button) findViewById(R.id.selectButton); final Button templateButton = (Button) findViewById(R.id.templateButton); final Button instructionButton = (Button) findViewById(R.id.instructionButton); final ImageView imageView = (ImageView) findViewById(R.id.imageView); try {//from w ww . j a va 2 s. c o m int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors(); Toast.makeText(this, NUMBER_OF_CORES, Toast.LENGTH_SHORT).show(); } catch (Exception e) { Log.e(TAG, "Processor-cores are not getting detected!"); } try { final Toast toast = Toast.makeText(this, "Please capture image; \n" + "select image; \n" + "Drag-and-drop, swipe on the desired region and confirm template!", Toast.LENGTH_LONG); final TextView v = (TextView) toast.getView().findViewById(android.R.id.message); instructionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { if (v != null) v.setGravity(Gravity.CENTER); toast.show(); } }); } catch (Exception e) { Log.e(TAG, "Instructions are not getting displayed!"); } try { cameraButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); startActivityForResult(intent, requestCode); } }); } catch (Exception e) { Log.e(TAG, "Camera is not working!"); } try { selectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, requestCode); bitmap = BitmapFactory.decodeFile(filePath); imageView.setImageBitmap(bitmap); } }); } catch (Exception e) { Log.e(TAG, "Selection is not working!"); } try { templateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { if (imageView.getDrawable() == null) { Log.e(TAG, "Null ImageView!"); } Log.e(TAG, "Button is working."); try { bitmap = BitmapFactory.decodeFile(filePath); bitmap = Bitmap.createScaledBitmap(bitmap, bitmapWidth, bitmapHeight, true); Mat frame = new Mat(bitmap.getWidth(), bitmap.getHeight(), CvType.CV_8UC4); Utils.bitmapToMat(bitmap, frame); GlobalClass globalVariable = (GlobalClass) getApplicationContext(); globalVariable.setTemplateCapturedBitmapHeight(bitmapHeight); globalVariable.setTemplateCapturedBitmapWidth(bitmapWidth); Log.e(TAG, "Bitmap has been set successfully; Template is being generated!"); rect = new Rect(x0final, y0final, x1final - x0final, y1final - y0final); Utils.matToBitmap(frame, bitmap); if (x0final < x1final) { x0display = x0final; x1display = x1final; } if (x0final > x1final) { x1display = x0final; x0display = x1final; } if (y0final < y1final) { y0display = y0final; y1display = y1final; } if (y0final > y1final) { y1display = y0final; y0display = y1final; } long timeBegin = (int) System.currentTimeMillis(); bitmap = Bitmap.createBitmap(bitmap, x0display, y0display, x1display - x0display, y1display - y0display); /*String path = Environment.getExternalStorageDirectory().toString(); Log.e(TAG, "File is about to be written!"); //File file = new File(path, "TraQuad"); //bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOutputStream); //Log.e(TAG, "Stored image successfully!"); //fOutputStream.flush(); //fOutputStream.close(); //MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());*/ /*Prominent colors code; This is not working in Android; OpenCV assertion error Log.e(TAG, "Retrieved image successfully!"); Imgproc.medianBlur(frame, frame, 3); Log.e(TAG, "Filtered image successfully!"); try { Mat mask = new Mat(bitmap.getWidth(), bitmap.getHeight(), CvType.CV_8UC1); MatOfFloat range = new MatOfFloat(0f, 255f); Mat hist = new Mat(); MatOfInt mHistSize = new MatOfInt(256); List<Mat> lHsv = new ArrayList<Mat>(3); Mat hsv = new Mat(); Imgproc.cvtColor(frame, hsv, Imgproc.COLOR_RGB2HSV); Core.split(frame, lHsv); Mat mH = lHsv.get(0); Mat mS = lHsv.get(1); Mat mV = lHsv.get(2); ArrayList<Mat> ListMat = new ArrayList<Mat>(); ListMat.add(mH); Log.e(TAG, String.valueOf(ListMat)); MatOfInt channels = new MatOfInt(0, 1); Imgproc.calcHist(Arrays.asList(mH), channels, mask, hist, mHistSize, range); ListMat.clear(); }catch (Exception e){ Log.e(TAG, "Prominent colors are not getting detected!"); }*/ Mat colorFrame = frame; colorFrame = frame.clone(); Utils.bitmapToMat(bitmap, frame); Imgproc.cvtColor(frame, frame, Imgproc.COLOR_RGB2GRAY); Log.e(TAG, "Converted color successfully!"); int detectorType = FeatureDetector.ORB; //int detectorType = FeatureDetector.SIFT; //SIFT and SURF are not working! //int detectorType = FeatureDetector.SURF; FeatureDetector featureDetector = FeatureDetector.create(detectorType); Log.e(TAG, "Feature detection has begun!"); MatOfKeyPoint keypoints = new MatOfKeyPoint(); featureDetector.detect(frame, keypoints); Log.e(TAG, "Feature detection has ended successfully!"); /*if (!featureDetector.empty()) { //Draw the detected keypoints int flagDraw = Features2d.NOT_DRAW_SINGLE_POINTS; Features2d.drawKeypoints(frame, keypoints, frame, color, flagDraw); Utils.matToBitmap(frame, bitmap); }*/ imageView.setImageBitmap(bitmap); Log.e(TAG, "Final bitmap has been loaded!"); KeyPoint[] referenceKeypoints = keypoints.toArray(); Log.e(TAG, "Number of keypoints detected is " + String.valueOf(referenceKeypoints.length)); int iterationMax = referenceKeypoints.length; int iterate = 0; double xFeaturePoint, yFeaturePoint; double xSum = 0, ySum = 0; double totalResponse = 0; double keyPointResponse = 0; double xTemplateCentroid = 0, yTemplateCentroid = 0; DescriptorExtractor descriptorExtractor = DescriptorExtractor .create(DescriptorExtractor.ORB); Mat templateDescriptor = new Mat(); descriptorExtractor.compute(frame, keypoints, templateDescriptor); for (iterate = 0; iterate < iterationMax; iterate++) { xFeaturePoint = referenceKeypoints[iterate].pt.x; yFeaturePoint = referenceKeypoints[iterate].pt.y; keyPointResponse = referenceKeypoints[iterate].response; if (keyPointResponse > 0) { xSum = xSum + keyPointResponse * xFeaturePoint; ySum = ySum + keyPointResponse * yFeaturePoint; totalResponse = totalResponse + keyPointResponse; //Log.e(TAG, "Feature " + String.valueOf(iterate) + ":" + String.valueOf(referenceKeypoints[iterate])); } } xTemplateCentroid = xSum / totalResponse; yTemplateCentroid = ySum / totalResponse; Log.e(TAG, "Finished conversion of features to points!"); Log.e(TAG, "Centroid location is: (" + xTemplateCentroid + "," + yTemplateCentroid + ")"); double xSquareDistance = 0, ySquareDistance = 0; double distanceTemplateFeatures = 0; int numberOfPositiveResponses = 0; double[] colorValue; double rSum = 0, gSum = 0, bSum = 0; double rCentral, gCentral, bCentral; for (iterate = 0; iterate < iterationMax; iterate++) { xFeaturePoint = referenceKeypoints[iterate].pt.x; yFeaturePoint = referenceKeypoints[iterate].pt.y; keyPointResponse = referenceKeypoints[iterate].response; colorValue = colorFrame.get((int) yFeaturePoint, (int) xFeaturePoint); rSum = rSum + colorValue[0]; gSum = gSum + colorValue[1]; bSum = bSum + colorValue[2]; if (keyPointResponse > 0) { xSquareDistance = xSquareDistance + (xFeaturePoint - xTemplateCentroid) * (xFeaturePoint - xTemplateCentroid); ySquareDistance = ySquareDistance + (yFeaturePoint - yTemplateCentroid) * (yFeaturePoint - yTemplateCentroid); numberOfPositiveResponses++; } } rCentral = rSum / iterationMax; gCentral = gSum / iterationMax; bCentral = bSum / iterationMax; double deltaColor = 21; double rLow = rCentral - deltaColor; double rHigh = rCentral + deltaColor; double gLow = rCentral - deltaColor; double gHigh = rCentral + deltaColor; double bLow = rCentral - deltaColor; double bHigh = rCentral + deltaColor; Log.e(TAG, "Prominent color (R,G,B): (" + rCentral + "," + gCentral + "," + bCentral + ")"); distanceTemplateFeatures = Math .sqrt((xSquareDistance + ySquareDistance) / numberOfPositiveResponses); KeyPoint[] offsetCompensatedKeyPoints = keypoints.toArray(); double xMaxNormalisation, yMaxNormalisation; xMaxNormalisation = x1display - x0display; yMaxNormalisation = y1display - y0display; for (iterate = 0; iterate < iterationMax; iterate++) { offsetCompensatedKeyPoints[iterate].pt.x = offsetCompensatedKeyPoints[iterate].pt.x / xMaxNormalisation; offsetCompensatedKeyPoints[iterate].pt.y = offsetCompensatedKeyPoints[iterate].pt.y / yMaxNormalisation; //Log.e(TAG, "Compensated: (" + String.valueOf(offsetCompensatedKeyPoints[iterate].pt.x) + "," + String.valueOf(offsetCompensatedKeyPoints[iterate].pt.y) + ")"); } double xCentroidNormalised, yCentroidNormalised; xCentroidNormalised = (xTemplateCentroid - x0display) / xMaxNormalisation; yCentroidNormalised = (yTemplateCentroid - y0display) / yMaxNormalisation; Log.e(TAG, "Normalised Centroid: (" + String.valueOf(xCentroidNormalised) + "," + String.valueOf(yCentroidNormalised)); long timeEnd = (int) System.currentTimeMillis(); Log.e(TAG, "Time consumed is " + String.valueOf(timeEnd - timeBegin) + " milli-seconds!"); Log.e(TAG, "RMS distance is: " + distanceTemplateFeatures); globalVariable.setDistanceTemplateFeatures(distanceTemplateFeatures); globalVariable.setX0display(x0display); globalVariable.setY0display(y0display); globalVariable.setX1display(x1display); globalVariable.setY1display(y1display); globalVariable.setKeypoints(keypoints); globalVariable.setXtemplateCentroid(xTemplateCentroid); globalVariable.setYtemplateCentroid(yTemplateCentroid); globalVariable.setTemplateDescriptor(templateDescriptor); globalVariable.setNumberOfTemplateFeatures(iterationMax); globalVariable.setNumberOfPositiveTemplateFeatures(numberOfPositiveResponses); globalVariable.setRhigh(rHigh); globalVariable.setRlow(rLow); globalVariable.setGhigh(gHigh); globalVariable.setGlow(gLow); globalVariable.setBhigh(bHigh); globalVariable.setBlow(bLow); globalVariable.setXnormalisedCentroid(xCentroidNormalised); globalVariable.setYnormalisedCentroid(yCentroidNormalised); globalVariable.setNormalisedTemplateKeyPoints(offsetCompensatedKeyPoints); Log.e(TAG, "Finished setting the global variables!"); } catch (Exception e) { Log.e(TAG, "Please follow instructions!"); } } }); } catch (Exception e) { Log.e(TAG, "Template is not working!"); } }
From source file:com.astrocytes.core.operationsengine.CoreOperations.java
License:Open Source License
/** * Remove all small contours on binary image with areas less than specified threshold. * * @param src - binary source image./* w ww. ja v a 2 s. c om*/ * @param thresh - minimum area of contour. * @return a source image with removed all contours with area less than {@param thresh}. */ public static Mat clearContours(Mat src, int thresh) { if (src.channels() > 1) return src; Mat dest = src.clone(); List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Mat hierarchy = new Mat(); findContours(src, contours, hierarchy, Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_TC89_L1); Mat maskWhite = new Mat(src.rows(), src.cols(), CvType.CV_8UC1, new Scalar(255)); Mat maskBlack = maskWhite.clone(); for (int i = 0; i < contours.size(); i++) { Double contourArea = contourArea(contours.get(i)); if (contourArea < thresh) { int pixelColor = averageIntensity(src, contours.get(i)); drawContours(pixelColor > 127 ? maskWhite : maskBlack, contours, i, new Scalar(0), Core.FILLED); } } maskWhite = erode(maskWhite, 2); maskBlack = erode(maskBlack, 2); dest = and(maskWhite, dest); dest = or(invert(maskBlack), dest); return dest; }
From source file:com.astrocytes.core.operationsengine.OperationsImpl.java
License:Open Source License
@Override public void setSourceImage(Mat sourceImage) { this.sourceImage = sourceImage; this.currentImage = sourceImage.clone(); this.astrocytesCenters = null; this.neurons = null; this.layerBounds = null; }