Java Code Examples for org.opencv.core.Core

The following examples show how to use org.opencv.core.Core. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: ml-authentication   Source File: RecognitionThread.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the recognized Student if the cosineSimilarity was above the threshold
 * @param featureVectorToRecognize
 * @return
 */
private synchronized List<Student> getMostSimilarStudentIfInThreshold(Mat featureVectorToRecognize){
    List<StudentImageCollectionEvent> studentImageCollectionEvents = studentImageCollectionEventDao.queryBuilder().where(StudentImageCollectionEventDao.Properties.MeanFeatureVector.isNotNull()).list();
    List<Student> studentsInThreshold = new ArrayList<>();
    for (StudentImageCollectionEvent studentImageCollectionEvent : studentImageCollectionEvents){
        Student currentStudent = studentImageCollectionEvent.getStudent();
        // Skip if the students are identical (same UniqueId)
        if (!areStudentsIdentical(currentStudent)){
            List<Float> featureVectorList = gson.fromJson(studentImageCollectionEvent.getMeanFeatureVector(), new TypeToken<List<Float>>(){}.getType());
            Mat featureVector = Converters.vector_float_to_Mat(featureVectorList);
            double dotProduct = featureVector.dot(featureVectorToRecognize);
            double normFeatureVector = Core.norm(featureVector, Core.NORM_L2);
            double normFeatureVectorToRecognize = Core.norm(featureVectorToRecognize, Core.NORM_L2);
            double cosineSimilarity = dotProduct / (normFeatureVector * normFeatureVectorToRecognize);
            double absoluteCosineSimilarity = Math.abs(cosineSimilarity);
            Log.i(getClass().getName(), "getMostSimilarStudentIfInThreshold: absoluteCosineSimilarity: " + absoluteCosineSimilarity + " with Student: " + currentStudent.getUniqueId());
            if (absoluteCosineSimilarity > SIMILARITY_THRESHOLD){
                studentsInThreshold.add(currentStudent);
            }
        } else {
            Log.i(getClass().getName(), "getMostSimilarStudentIfInThreshold: currentStudent: " + currentStudent.getUniqueId() + " was skipped because it is identical with the student: " + student.getUniqueId());
        }
    }
    return studentsInThreshold;
}
 
Example 2
Source Project: MOAAP   Source File: FpsMeter.java    License: MIT License 6 votes vote down vote up
public void measure() {
    if (!mIsInitialized) {
        init();
        mIsInitialized = true;
    } else {
        mFramesCouner++;
        if (mFramesCouner % STEP == 0) {
            long time = Core.getTickCount();
            double fps = STEP * mFrequency / (time - mprevFrameTime);
            mprevFrameTime = time;
            if (mWidth != 0 && mHeight != 0)
                mStrfps = FPS_FORMAT.format(fps) + " [email protected]" + Integer.valueOf(mWidth) + "x" + Integer.valueOf(mHeight);
            else
                mStrfps = FPS_FORMAT.format(fps) + " FPS";
            Log.i(TAG, mStrfps);
        }
    }
}
 
Example 3
Source Project: MOAAP   Source File: FpsMeter.java    License: MIT License 6 votes vote down vote up
public void measure() {
    if (!mIsInitialized) {
        init();
        mIsInitialized = true;
    } else {
        mFramesCouner++;
        if (mFramesCouner % STEP == 0) {
            long time = Core.getTickCount();
            double fps = STEP * mFrequency / (time - mprevFrameTime);
            mprevFrameTime = time;
            if (mWidth != 0 && mHeight != 0)
                mStrfps = FPS_FORMAT.format(fps) + " [email protected]" + Integer.valueOf(mWidth) + "x" + Integer.valueOf(mHeight);
            else
                mStrfps = FPS_FORMAT.format(fps) + " FPS";
            Log.i(TAG, mStrfps);
        }
    }
}
 
Example 4
Source Project: AndroidDocumentScanner   Source File: FpsMeter.java    License: MIT License 6 votes vote down vote up
public void measure() {
    if (!mIsInitialized) {
        init();
        mIsInitialized = true;
    } else {
        mFramesCouner++;
        if (mFramesCouner % STEP == 0) {
            long time = Core.getTickCount();
            double fps = STEP * mFrequency / (time - mprevFrameTime);
            mprevFrameTime = time;
            if (mWidth != 0 && mHeight != 0)
                mStrfps = FPS_FORMAT.format(fps) + " [email protected]" + Integer.valueOf(mWidth) + "x" + Integer.valueOf(mHeight);
            else
                mStrfps = FPS_FORMAT.format(fps) + " FPS";
            Log.i(TAG, mStrfps);
        }
    }
}
 
Example 5
Source Project: OpenCV-AndroidSamples   Source File: ComparisonFrameRender.java    License: MIT License 6 votes vote down vote up
@Override
public Mat render(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
    Mat undistortedFrame = new Mat(inputFrame.rgba().size(), inputFrame.rgba().type());
    Imgproc.undistort(inputFrame.rgba(), undistortedFrame,
            mCalibrator.getCameraMatrix(), mCalibrator.getDistortionCoefficients());

    Mat comparisonFrame = inputFrame.rgba();
    undistortedFrame.colRange(new Range(0, mWidth / 2)).copyTo(comparisonFrame.colRange(new Range(mWidth / 2, mWidth)));
    List<MatOfPoint> border = new ArrayList<MatOfPoint>();
    final int shift = (int)(mWidth * 0.005);
    border.add(new MatOfPoint(new Point(mWidth / 2 - shift, 0), new Point(mWidth / 2 + shift, 0),
            new Point(mWidth / 2 + shift, mHeight), new Point(mWidth / 2 - shift, mHeight)));
    Imgproc.fillPoly(comparisonFrame, border, new Scalar(255, 255, 255));

    Imgproc.putText(comparisonFrame, mResources.getString(R.string.original), new Point(mWidth * 0.1, mHeight * 0.1),
            Core.FONT_HERSHEY_SIMPLEX, 1.0, new Scalar(255, 255, 0));
    Imgproc.putText(comparisonFrame, mResources.getString(R.string.undistorted), new Point(mWidth * 0.6, mHeight * 0.1),
            Core.FONT_HERSHEY_SIMPLEX, 1.0, new Scalar(255, 255, 0));

    return comparisonFrame;
}
 
Example 6
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
    Mat imgRgba = inputFrame.rgba();
    Mat img = new Mat();
    imgRgba.copyTo(img);
    List<Mat> images = ppF.getProcessedImage(img, PreProcessorFactory.PreprocessingMode.RECOGNITION);
    Rect[] faces = ppF.getFacesForRecognition();

    // Selfie / Mirror mode
    if(front_camera){
        Core.flip(imgRgba,imgRgba,1);
    }
    if(images == null || images.size() == 0 || faces == null || faces.length == 0 || ! (images.size() == faces.length)){
        // skip
        return imgRgba;
    } else {
        faces = MatOperation.rotateFaces(imgRgba, faces, ppF.getAngleForRecognition());
        for(int i = 0; i<faces.length; i++){
            MatOperation.drawRectangleAndLabelOnPreview(imgRgba, faces[i], rec.recognize(images.get(i), ""), front_camera);
        }
        return imgRgba;
    }
}
 
Example 7
public void processPicture( Mat picture ) {

        Mat img = Imgcodecs.imdecode(picture, Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);
        picture.release();

        Log.d(TAG, "processPicture - imported image " + img.size().width + "x" + img.size().height);

        if (mBugRotate) {
            Core.flip(img, img, 1 );
            Core.flip(img, img, 0 );
        }

        ScannedDocument doc = detectDocument(img);
        mMainActivity.saveDocument(doc);

        doc.release();
        picture.release();

        mMainActivity.setImageProcessorBusy(false);
        mMainActivity.waitSpinnerInvisible();
    }
 
Example 8
public void measure() {
    if (!mIsInitialized) {
        init();
        mIsInitialized = true;
    } else {
        mFramesCouner++;
        if (mFramesCouner % STEP == 0) {
            long time = Core.getTickCount();
            double fps = STEP * mFrequency / (time - mprevFrameTime);
            mprevFrameTime = time;
            if (mWidth != 0 && mHeight != 0)
                mStrfps = FPS_FORMAT.format(fps) + " [email protected]" + Integer.valueOf(mWidth) + "x" + Integer.valueOf(mHeight);
            else
                mStrfps = FPS_FORMAT.format(fps) + " FPS";
            Log.i(TAG, mStrfps);
        }
    }
}
 
Example 9
Source Project: faceswap   Source File: FpsMeter.java    License: Apache License 2.0 6 votes vote down vote up
public void measure() {
    if (!mIsInitialized) {
        init();
        mIsInitialized = true;
    } else {
        mFramesCouner++;
        if (mFramesCouner % STEP == 0) {
            long time = Core.getTickCount();
            double fps = STEP * mFrequency / (time - mprevFrameTime);
            mprevFrameTime = time;
            if (mWidth != 0 && mHeight != 0)
                mStrfps = FPS_FORMAT.format(fps) + " [email protected]" + Integer.valueOf(mWidth) + "x" + Integer.valueOf(mHeight);
            else
                mStrfps = FPS_FORMAT.format(fps) + " FPS";
            Log.i(TAG, mStrfps);
        }
    }
}
 
Example 10
Source Project: go-bees   Source File: TestUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Checks if two OpenCV Mats are equal.
 * The matrices must be equal size and type.
 * Floating-point mats are not supported.
 *
 * @param expected expected mat.
 * @param actual   actual mat.
 * @return true if they are equal.
 */
private static boolean equals(Mat expected, Mat actual) {
    if (expected.type() != actual.type() || expected.cols() != actual.cols()
            || expected.rows() != actual.rows()) {
        throw new UnsupportedOperationException(
                "Can not compare " + expected + " and " + actual);
    } else if (expected.depth() == CvType.CV_32F || expected.depth() == CvType.CV_64F) {
        throw new UnsupportedOperationException(
                "Floating-point mats must not be checked for exact match.");
    }
    // Subtract matrices
    Mat diff = new Mat();
    Core.absdiff(expected, actual, diff);
    // Count non zero pixels
    Mat reshaped = diff.reshape(1); // One channel
    int mistakes = Core.countNonZero(reshaped);
    // Free
    reshaped.release();
    diff.release();
    // Check mistakes
    return 0 == mistakes;
}
 
Example 11
Source Project: OpenCV-android   Source File: FpsMeter.java    License: Apache License 2.0 6 votes vote down vote up
public void measure() {
    if (!mIsInitialized) {
        init();
        mIsInitialized = true;
    } else {
        mFramesCouner++;
        if (mFramesCouner % STEP == 0) {
            long time = Core.getTickCount();
            double fps = STEP * mFrequency / (time - mprevFrameTime);
            mprevFrameTime = time;
            if (mWidth != 0 && mHeight != 0)
                mStrfps = FPS_FORMAT.format(fps) + " [email protected]" + Integer.valueOf(mWidth) + "x" + Integer.valueOf(mHeight);
            else
                mStrfps = FPS_FORMAT.format(fps) + " FPS";
            Log.i(TAG, mStrfps);
        }
    }
}
 
Example 12
Source Project: OpenCvFaceDetect   Source File: FpsMeter.java    License: Apache License 2.0 6 votes vote down vote up
public void measure() {
    if (!mIsInitialized) {
        init();
        mIsInitialized = true;
    } else {
        mFramesCouner++;
        if (mFramesCouner % STEP == 0) {
            long time = Core.getTickCount();
            double fps = STEP * mFrequency / (time - mprevFrameTime);
            mprevFrameTime = time;
            if (mWidth != 0 && mHeight != 0)
                mStrfps = FPS_FORMAT.format(fps) + " [email protected]" + Integer.valueOf(mWidth) + "x" + Integer.valueOf(mHeight);
            else
                mStrfps = FPS_FORMAT.format(fps) + " FPS";
            Log.i(TAG, mStrfps);
        }
    }
}
 
Example 13
Source Project: FTCVision   Source File: FpsMeter.java    License: MIT License 6 votes vote down vote up
public void measure() {
    if (!mIsInitialized) {
        init();
        mIsInitialized = true;
    } else {
        mFramesCouner++;
        if (mFramesCouner % STEP == 0) {
            long time = Core.getTickCount();
            double fps = STEP * mFrequency / (time - mprevFrameTime);
            mprevFrameTime = time;
            if (mWidth != 0 && mHeight != 0)
                mStrfps = FPS_FORMAT.format(fps) + " [email protected]" + Integer.valueOf(mWidth) + "x" + Integer.valueOf(mHeight);
            else
                mStrfps = FPS_FORMAT.format(fps) + " FPS";
            Log.i(TAG, mStrfps);
        }
    }
}
 
Example 14
@Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
    Mat imgRgba = inputFrame.rgba();
    Mat img = new Mat();
    imgRgba.copyTo(img);
    List<Mat> images = ppF.getCroppedImage(img);
    Rect[] faces = ppF.getFacesForRecognition();

    // Selfie / Mirror mode
    if(front_camera){
        Core.flip(imgRgba,imgRgba,1);
    }
    if(images == null || images.size() == 0 || faces == null || faces.length == 0 || ! (images.size() == faces.length)){
        // skip
        return imgRgba;
    } else {
        faces = MatOperation.rotateFaces(imgRgba, faces, ppF.getAngleForRecognition());
        for(int i = 0; i<faces.length; i++){
            MatOperation.drawRectangleAndLabelOnPreview(imgRgba, faces[i], "", front_camera);
        }
        return imgRgba;
    }
}
 
Example 15
Source Project: Java-for-Data-Science   Source File: OpenCVNonMavenExamples.java    License: MIT License 6 votes vote down vote up
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 16
Source Project: OpenCV-AndroidSamples   Source File: CameraCalibrator.java    License: MIT License 6 votes vote down vote up
public void calibrate() {
    ArrayList<Mat> rvecs = new ArrayList<Mat>();
    ArrayList<Mat> tvecs = new ArrayList<Mat>();
    Mat reprojectionErrors = new Mat();
    ArrayList<Mat> objectPoints = new ArrayList<Mat>();
    objectPoints.add(Mat.zeros(mCornersSize, 1, CvType.CV_32FC3));
    calcBoardCornerPositions(objectPoints.get(0));
    for (int i = 1; i < mCornersBuffer.size(); i++) {
        objectPoints.add(objectPoints.get(0));
    }

    Calib3d.calibrateCamera(objectPoints, mCornersBuffer, mImageSize,
            mCameraMatrix, mDistortionCoefficients, rvecs, tvecs, mFlags);

    mIsCalibrated = Core.checkRange(mCameraMatrix)
            && Core.checkRange(mDistortionCoefficients);

    mRms = computeReprojectionErrors(objectPoints, rvecs, tvecs, reprojectionErrors);
    Log.i(TAG, String.format("Average re-projection error: %f", mRms));
    Log.i(TAG, "Camera matrix: " + mCameraMatrix.dump());
    Log.i(TAG, "Distortion coefficients: " + mDistortionCoefficients.dump());
}
 
Example 17
public String recognize(Mat img, String expectedLabel){
    // Ignore
    img = img.reshape(1,1);
    // Subtract mean
    img.convertTo(img, CvType.CV_32F);
    Core.subtract(img, Psi, img);
    // Project to subspace
    Mat projected = getFeatureVector(img);
    // Save all points of image for tSNE
    img.convertTo(img, CvType.CV_8U);
    addImage(projected, expectedLabel, true);
    //addImage(projected, expectedLabel);
    Mat distance = new Mat(Omega.rows(), 1, CvType.CV_64FC1);
    for (int i=0; i<Omega.rows(); i++){
        double dist = Core.norm(projected.row(0), Omega.row(i), Core.NORM_L2);
        distance.put(i, 0, dist);
    }
    Mat sortedDist = new Mat(Omega.rows(), 1, CvType.CV_8UC1);
    Core.sortIdx(distance, sortedDist, Core.SORT_EVERY_COLUMN + Core.SORT_ASCENDING);
    // Give back the name of the found person
    int index = (int)(sortedDist.get(0,0)[0]);
    return labelMap.getKey(labelList.get(index));
}
 
Example 18
Source Project: FTCVision   Source File: Detectable.java    License: MIT License 6 votes vote down vote up
/**
 * Gets the average color of the object
 *
 * @param img      The image matrix, of any color size
 * @param imgSpace The image's color space
 * @return The average color of the region
 */
public Color averageColor(Mat img, ColorSpace imgSpace) {
    //Coerce values to stay within screen dimensions
    double leftX = MathUtil.coerce(0, img.cols() - 1, left());
    double rightX = MathUtil.coerce(0, img.cols() - 1, right());

    double topY = MathUtil.coerce(0, img.rows() - 1, top());
    double bottomY = MathUtil.coerce(0, img.rows() - 1, bottom());

    //Input points into array for calculation
    //TODO rectangular submatrix-based calculation isn't perfectly accurate when you have ellipses or weird shapes
    Mat subMat = img.submat((int) topY, (int) bottomY, (int) leftX, (int) rightX);

    //Calculate average and return new color instance
    return Color.create(Core.mean(subMat), imgSpace);
}
 
Example 19
Source Project: DogeCV   Source File: HSVColorFilter.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 20
Source Project: sudokufx   Source File: FpsMeter.java    License: Apache License 2.0 5 votes vote down vote up
public void init() {
    mFramesCouner = 0;
    mFrequency = Core.getTickFrequency();
    mprevFrameTime = Core.getTickCount();
    mStrfps = "";

    mPaint = new Paint();
    mPaint.setColor(Color.BLUE);
    mPaint.setTextSize(20);
}
 
Example 21
Source Project: OpenCV-AndroidSamples   Source File: ColorBlobDetector.java    License: MIT License 5 votes vote down vote up
public void process(Mat rgbaImage) {
    Imgproc.pyrDown(rgbaImage, mPyrDownMat);
    Imgproc.pyrDown(mPyrDownMat, mPyrDownMat);

    Imgproc.cvtColor(mPyrDownMat, mHsvMat, Imgproc.COLOR_RGB2HSV_FULL);

    Core.inRange(mHsvMat, mLowerBound, mUpperBound, mMask);
    Imgproc.dilate(mMask, mDilatedMask, new Mat());

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

    Imgproc.findContours(mDilatedMask, contours, mHierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    // Find max contour area
    double maxArea = 0;
    Iterator<MatOfPoint> each = contours.iterator();
    while (each.hasNext()) {
        MatOfPoint wrapper = each.next();
        double area = Imgproc.contourArea(wrapper);
        if (area > maxArea)
            maxArea = area;
    }

    // Filter contours by area and resize to fit the original image size
    mContours.clear();
    each = contours.iterator();
    while (each.hasNext()) {
        MatOfPoint contour = each.next();
        if (Imgproc.contourArea(contour) > mMinContourArea*maxArea) {
            Core.multiply(contour, new Scalar(4,4), contour);
            mContours.add(contour);
        }
    }
}
 
Example 22
Source Project: LPR   Source File: FpsMeter.java    License: Apache License 2.0 5 votes vote down vote up
public void init() {
    mFramesCounter = 0;
    mFrequency = Core.getTickFrequency();
    mprevFrameTime = Core.getTickCount();
    mStrfps = "";

    mPaint = new Paint();
    mPaint.setColor(Color.BLUE);
    mPaint.setTextSize(20);
}
 
Example 23
Source Project: OpenTLDAndroid   Source File: Tld.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Output: resized zero-mean patch/pattern
 * @param inImg INPUT, outPattern OUTPUT
 * @return stdev
 */
private static double resizeZeroMeanStdev(final Mat inImg, Mat outPattern, int patternSize){
	if(inImg == null || outPattern == null){
		return -1;
	}
	
	Imgproc.resize(inImg, outPattern, new Size(patternSize, patternSize));
	final MatOfDouble mean = new MatOfDouble();
	final MatOfDouble stdev = new MatOfDouble();
	Core.meanStdDev(outPattern, mean, stdev);
	outPattern.convertTo(outPattern, CvType.CV_32F);
	Core.subtract(outPattern, new Scalar(mean.toArray()[0]), outPattern);
	
	return stdev.toArray()[0];
}
 
Example 24
Source Project: OptimizedImageEnhance   Source File: DarkChannelPriorDehaze.java    License: MIT License 5 votes vote down vote up
private static Mat dehaze(Mat channel, Mat t, double minAtmosLight) {
	Mat t_ = new Mat();
	Core.subtract(t, new Scalar(1.0), t_);
	Core.multiply(t_, new Scalar(-1.0 * minAtmosLight), t_);
	Core.subtract(channel, t_, channel);
	Core.divide(channel, t, channel);
	return channel;
}
 
Example 25
Source Project: OpenCV-AndroidSamples   Source File: FpsMeter.java    License: MIT License 5 votes vote down vote up
public void init() {
    mFramesCouner = 0;
    mFrequency = Core.getTickFrequency();
    mprevFrameTime = Core.getTickCount();
    mStrfps = "";

    mPaint = new Paint();
    mPaint.setColor(Color.BLUE);
    mPaint.setTextSize(20);
}
 
Example 26
/**
 * @return true if motion was detected compared to the last frame
 */
public boolean detect(Mat frame) {
	if(lastImage == null) {
		lastImage = frame.clone();
		return true;
	}
	
	Mat diff = new Mat();
	Core.absdiff(lastImage, frame, diff);
	Imgproc.threshold(diff, diff, 35, 255, Imgproc.THRESH_BINARY);
	
	// extract color channels and merge them to single bitmask
	Mat r = ColorSpace.getChannel(diff, 2);
	Mat g = ColorSpace.getChannel(diff, 1);
	Mat b = ColorSpace.getChannel(diff, 0);

	mask = r.clone();
	Core.add(mask, g, mask);
	Core.add(mask, b, mask);
	
	float changes = Core.countNonZero(mask) / (float)( frame.cols() * frame.rows());
	r.release();
	g.release();
	b.release();
	lastImage.release();
	lastImage = frame.clone();
	return thresholdPercentage < changes;
}
 
Example 27
Source Project: OpenTLDAndroid   Source File: PatchGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
	 * 
	 * @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 28
Source Project: classchecks   Source File: Recognition.java    License: Apache License 2.0 5 votes vote down vote up
public static Mat subspaceReconstruct(Mat W, Mat mean, Mat src) {
	int n = src.rows();
	int d = src.cols();
	Mat X = new Mat();
	Mat Y = new Mat();
	src.convertTo(Y, W.type());
	Core.gemm(Y, W, 1.0, new Mat(), 0.0, X, 2);
	if(!mean.empty()) {
		for(int i = 0; i < n; i ++) {
			Mat r_i = X.row(i);
			Core.add(r_i, mean.reshape(1, 1), r_i);
		}
	}
	return X;
}
 
Example 29
public Mat drawBoxes(List<Classifier.Recognition> boxes, double confidenceThreshold){
        rgbImage.copyTo(boxesImage);
        Scalar color;


        for (Classifier.Recognition box : boxes) {
            Log.i(TAG, String.valueOf(box));
            if (box.getTitle().equals("person")) {
                if (box.getConfidence() > confidenceThreshold) {
//                color.val[0] = (color.val[0] + 25) % 255;
//                color.val[1] = (color.val[1] + 35) % 255;
//                color.val[2] = (color.val[2] + 45) % 255;
                    color = colors.get(box.getTitle());

                    Point pt1 = new Point(box.getLocation().left * widthRatio, box.getLocation().top * heightRatio);
                    Point pt2 = new Point(box.getLocation().right * widthRatio, box.getLocation().bottom * heightRatio);
                    Imgproc.rectangle(boxesImage, pt1, pt2, color, 3, 8);
                    Point pt3 = new Point(box.getLocation().left * widthRatio, box.getLocation().top * heightRatio);
                    Point pt4 = new Point(Math.min(box.getLocation().right, box.getLocation().left + (box.getTitle().length() * 13)) * widthRatio, (box.getLocation().top + 11) * heightRatio);
                    Imgproc.rectangle(boxesImage, pt3, pt4, color, FILLED, 8);

                    pt1.set(new double[]{pt1.x + 2 * heightRatio, (pt1.y + 10 * heightRatio)});
                    Imgproc.putText(boxesImage, box.getTitle(), pt1, Core.FONT_HERSHEY_SIMPLEX, 0.4 * heightRatio, (isLight(color) ? BLACK : WHITE), (int) (1 * heightRatio), LINE_AA);
                }
            }
        }

        return boxesImage;
    }
 
Example 30
Source Project: ImageEnhanceViaFusion   Source File: Pyramid.java    License: MIT License 5 votes vote down vote up
public static Mat PyramidReconstruct(Mat[] pyramid) {
	int level = pyramid.length;
	for (int i = level - 1; i > 0; i--) {
		Mat tmpPyr = new Mat();
		Imgproc.resize(pyramid[i], tmpPyr, pyramid[i - 1].size(), 0, 0, Imgproc.INTER_LINEAR);
		Core.add(pyramid[i - 1], tmpPyr, pyramid[i - 1]);
	}
	return pyramid[0];
}