Java Code Examples for org.opencv.core.Mat#size()

The following examples show how to use org.opencv.core.Mat#size() . 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: ImageProcessor.java    From Document-Scanner with GNU General Public License v3.0 7 votes vote down vote up
private void enhanceDocument( Mat src ) {
    if (colorMode && filterMode) {
        src.convertTo(src,-1, colorGain , colorBias);
        Mat mask = new Mat(src.size(), CvType.CV_8UC1);
        Imgproc.cvtColor(src,mask,Imgproc.COLOR_RGBA2GRAY);

        Mat copy = new Mat(src.size(), CvType.CV_8UC3);
        src.copyTo(copy);

        Imgproc.adaptiveThreshold(mask,mask,255,Imgproc.ADAPTIVE_THRESH_MEAN_C,Imgproc.THRESH_BINARY_INV,15,15);

        src.setTo(new Scalar(255,255,255));
        copy.copyTo(src,mask);

        copy.release();
        mask.release();

        // special color threshold algorithm
        colorThresh(src,colorThresh);
    } else if (!colorMode) {
        Imgproc.cvtColor(src,src,Imgproc.COLOR_RGBA2GRAY);
        if (filterMode) {
            Imgproc.adaptiveThreshold(src, src, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 15, 15);
        }
    }
}
 
Example 2
Source File: Beacon.java    From FTCVision with MIT License 6 votes vote down vote up
/**
 * Analyze the current frame using the selected analysis method, using custom color blob detectors
 *
 * @param redDetector  Red color blob detector
 * @param blueDetector Blue color blob detector
 * @param img          Image to analyze
 * @param gray         Grayscale image to analyze
 * @param orientation  Screen orientation compensation, given by the android.Sensors class
 * @return Beacon analysis class
 */
public BeaconAnalysis analyzeFrame(ColorBlobDetector redDetector, ColorBlobDetector blueDetector, Mat img, Mat gray, ScreenOrientation orientation) {
    if (this.bounds == null)
        this.bounds = new Rectangle(img.size());
    switch (method) {
        case REALTIME:
            blueDetector.process(img);
            redDetector.process(img);
            return BeaconAnalyzer.analyze_REALTIME(redDetector.getContours(), blueDetector.getContours(), img, orientation, this.debug);
        case FAST:
        case DEFAULT:
        default:
            return BeaconAnalyzer.analyze_FAST(redDetector, blueDetector, img, gray, orientation, this.bounds, this.debug);
        case COMPLEX:
            blueDetector.process(img);
            redDetector.process(img);
            return BeaconAnalyzer.analyze_COMPLEX(redDetector.getContours(), blueDetector.getContours(), img, gray, orientation, this.bounds, this.debug);
    }
}
 
Example 3
Source File: StepByStepTestActivity.java    From CVScanner with GNU General Public License v3.0 6 votes vote down vote up
Mat buildSkeleton(Mat img){
    Mat morph = Imgproc.getStructuringElement(Imgproc.CV_SHAPE_CROSS, new Size(3, 3));
    Mat skel = new Mat(img.size(), CvType.CV_8UC1, Scalar.all(0));
    Mat eroded = new Mat();
    Mat temp = new Mat();

    boolean done = false;

    do{
        Imgproc.morphologyEx(img, eroded, Imgproc.MORPH_ERODE, morph);
        Imgproc.morphologyEx(eroded, temp, Imgproc.MORPH_DILATE, morph);
        Core.subtract(img, temp, temp);
        Core.bitwise_or(skel, temp, skel);
        eroded.copyTo(img);

        done = Core.countNonZero(img) == 0;
    }while (!done);

    return skel;
}
 
Example 4
Source File: DogeCVDetector.java    From DogeCV with GNU General Public License v3.0 6 votes vote down vote up
@Override
public final Mat processFrame(Mat input) {
    size = input.size();

    Log.d("DogeCVDetector", "Input mat size:" + input.size());
    input.copyTo(workingMat);

    if(workingMat.empty()){
        return input;
    }

    workingMat = process(workingMat);

    //Print Info
    Imgproc.putText(workingMat,"DogeCV 2020.1 " + detectorName + ": " + stageToRenderToViewport.toString(), new Point(5,30),0,0.5,new Scalar(0,255,255),2);

    return workingMat;
}
 
Example 5
Source File: Recognition.java    From classchecks with Apache License 2.0 6 votes vote down vote up
/**
 * 
* @Title: reconstructFace 
* @Description: 从输入的预处理图像在人脸模型中重构人脸
* @param model 包含预处理的人脸模型
* @param preprocessedFace 输入的预处理过的图像
* @return
* Mat 
* @throws
 */
public static Mat reconstructFace(BasicFaceRecognizer model, Mat preprocessedFace){
	try {
		// 获取每个人脸的特征值
		Mat eigenvectors = model.getEigenVectors();
		// 获取平均人脸
		Mat averageFaceRow = model.getMean();
		int faceHeight = preprocessedFace.rows();
		// subspaceProject将人脸图像投影到特征空间
		Mat projection = subspaceProject(eigenvectors, averageFaceRow, preprocessedFace.reshape(1, 1));
		// subspaceReconstruct从特征空间重构图像
		Mat reconstructionRow = subspaceReconstruct(eigenvectors, averageFaceRow, projection);
		
		Mat reconstructionMat = reconstructionRow.reshape(1, faceHeight);
		Mat reconstructedFace = new Mat(reconstructionMat.size(), CvType.CV_8U);
		reconstructionMat.convertTo(reconstructedFace, CvType.CV_8U, 1, 0);
		
		return reconstructedFace;
	} catch(CvException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 6
Source File: OpenCVoperation.java    From Human-hair-detection with Apache License 2.0 5 votes vote down vote up
public  Mat quantizeImage(Mat image,String destinationFileName)
{
    //Mat image  = testGrabCut(imageFilePath);
    int rows = image.rows();
    int cols = image.cols();
    Mat newImage = new Mat(image.size(),image.type());
    for(int r = 0 ; r < rows ; r++)
    {
        for(int c =0; c< cols; c++)
        {
            double [] pixel_val = image.get(r, c);
            double [] pixel_data = new double[3];
            pixel_data[0] = reduceVal(pixel_val[0]);
            pixel_data[1] = reduceVal(pixel_val[1]);
            pixel_data[2] = reduceVal(pixel_val[2]);
         //   System.out.print("(" +pixel_data[0]+","+pixel_data[1]+","+pixel_data[2]+") *");
            newImage.put(r, c, pixel_data);
        }
      //  System.out.println();
    }
    /*
    MatOfInt params= new MatOfInt();
    int arr[] = new int[2];
    arr[0]= Imgcodecs.CV_IMWRITE_JPEG_QUALITY;
    arr[1]= 100;
    params.fromArray(arr);
    */
    Imgcodecs.imwrite(resultDirectory+destinationFileName, newImage);
    return newImage;
}
 
Example 7
Source File: Transform.java    From FTCVision with MIT License 5 votes vote down vote up
private static void resize(Mat img, Size size) {
    int interpolation;
    if (MathUtil.equal(size.area(), img.size().area()))
        return;
    else if (size.width > img.size().width && size.height > img.size().height)
        interpolation = Imgproc.CV_INTER_CUBIC; //enlarge image
    else if (size.width < img.size().width && size.height < img.size().height)
        interpolation = Imgproc.CV_INTER_AREA; //shrink image
    else
        interpolation = Imgproc.CV_INTER_LINEAR; //not entirely sure, so use safe option
    Imgproc.resize(img, img, size, 0, 0, interpolation);
}
 
Example 8
Source File: MainActivity.java    From SimpleDocumentScanner-Android with MIT License 5 votes vote down vote up
/**
 * NOTE:
 * Based off of http://www.pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/
 *
 * @param src
 * @param pts
 * @return
 */
private Mat fourPointTransform(Mat src, Point[] pts) {
    double ratio = src.size().height / (double) MAX_HEIGHT;

    Point ul = pts[0];
    Point ur = pts[1];
    Point lr = pts[2];
    Point ll = pts[3];

    double widthA = Math.sqrt(Math.pow(lr.x - ll.x, 2) + Math.pow(lr.y - ll.y, 2));
    double widthB = Math.sqrt(Math.pow(ur.x - ul.x, 2) + Math.pow(ur.y - ul.y, 2));
    double maxWidth = Math.max(widthA, widthB) * ratio;

    double heightA = Math.sqrt(Math.pow(ur.x - lr.x, 2) + Math.pow(ur.y - lr.y, 2));
    double heightB = Math.sqrt(Math.pow(ul.x - ll.x, 2) + Math.pow(ul.y - ll.y, 2));
    double maxHeight = Math.max(heightA, heightB) * ratio;

    Mat resultMat = new Mat(Double.valueOf(maxHeight).intValue(), Double.valueOf(maxWidth).intValue(), CvType.CV_8UC4);

    Mat srcMat = new Mat(4, 1, CvType.CV_32FC2);
    Mat dstMat = new Mat(4, 1, CvType.CV_32FC2);
    srcMat.put(0, 0, ul.x * ratio, ul.y * ratio, ur.x * ratio, ur.y * ratio, lr.x * ratio, lr.y * ratio, ll.x * ratio, ll.y * ratio);
    dstMat.put(0, 0, 0.0, 0.0, maxWidth, 0.0, maxWidth, maxHeight, 0.0, maxHeight);

    Mat M = Imgproc.getPerspectiveTransform(srcMat, dstMat);
    Imgproc.warpPerspective(src, resultMat, M, resultMat.size());

    srcMat.release();
    dstMat.release();
    M.release();

    return resultMat;
}
 
Example 9
Source File: CVProcessor.java    From CVScanner with GNU General Public License v3.0 5 votes vote down vote up
public static List<MatOfPoint> findContoursForMRZ(Mat src){
    Mat img = src.clone();
    src.release();
    double ratio = getScaleRatio(img.size());
    int width = (int) (img.size().width / ratio);
    int height = (int) (img.size().height / ratio);
    Size newSize = new Size(width, height);
    Mat resizedImg = new Mat(newSize, CvType.CV_8UC4);
    Imgproc.resize(img, resizedImg, newSize);

    Mat gray = new Mat();
    Imgproc.cvtColor(resizedImg, gray, Imgproc.COLOR_BGR2GRAY);
    Imgproc.medianBlur(gray, gray, 3);
    //Imgproc.blur(gray, gray, new Size(3, 3));

    Mat morph = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(13, 5));
    Mat dilatedImg = new Mat();
    Imgproc.morphologyEx(gray, dilatedImg, Imgproc.MORPH_BLACKHAT, morph);
    gray.release();

    Mat gradX = new Mat();
    Imgproc.Sobel(dilatedImg, gradX, CvType.CV_32F, 1, 0);
    dilatedImg.release();
    Core.convertScaleAbs(gradX, gradX, 1, 0);
    Core.MinMaxLocResult minMax = Core.minMaxLoc(gradX);
    Core.convertScaleAbs(gradX, gradX, (255/(minMax.maxVal - minMax.minVal)),
            - ((minMax.minVal * 255) / (minMax.maxVal - minMax.minVal)));
    Imgproc.morphologyEx(gradX, gradX, Imgproc.MORPH_CLOSE, morph);

    Mat thresh = new Mat();
    Imgproc.threshold(gradX, thresh, 0, 255, Imgproc.THRESH_OTSU);
    gradX.release();
    morph.release();

    morph = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(21, 21));
    Imgproc.morphologyEx(thresh, thresh, Imgproc.MORPH_CLOSE, morph);
    Imgproc.erode(thresh, thresh, new Mat(), new Point(-1, -1), 4);
    morph.release();

    int col = (int) resizedImg.size().width;
    int p = (int) (resizedImg.size().width * 0.05);
    int row = (int) resizedImg.size().height;
    for(int i = 0; i < row; i++)
    {
        for(int j = 0; j < p; j++){
            thresh.put(i, j, 0);
            thresh.put(i, col-j, 0);
        }
    }

    List<MatOfPoint> contours = new ArrayList<>();
    Mat hierarchy = new Mat();
    Imgproc.findContours(thresh, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
    hierarchy.release();

    Log.d(TAG, "contours found: " + contours.size());

    Collections.sort(contours, new Comparator<MatOfPoint>() {
        @Override
        public int compare(MatOfPoint o1, MatOfPoint o2) {
            return Double.valueOf(Imgproc.contourArea(o2)).compareTo(Imgproc.contourArea(o1));
        }
    });

    return contours;
}
 
Example 10
Source File: DctConverter.java    From BlindWatermark with Apache License 2.0 5 votes vote down vote up
@Override
public void addImageWatermark(Mat com, Mat watermark) {
    Mat mask = new Mat();
    inRange(watermark, new Scalar(0, 0, 0, 0), new Scalar(0, 0, 0, 0), mask);
    Mat i2 = new Mat(watermark.size(), watermark.type(), new Scalar(2, 2, 2, 0));
    i2.copyTo(watermark, mask);
    watermark.convertTo(watermark, CV_32F);
    int row = (com.rows() - watermark.rows()) >> 1;
    int col = (com.cols() - watermark.cols()) >> 1;
    copyMakeBorder(watermark, watermark, row, row, col, col, BORDER_CONSTANT, Scalar.all(0));
    Utils.fixSize(watermark, com);
    addWeighted(watermark, 0.03, com, 1, 0.0, com);
}
 
Example 11
Source File: ObjectDetector.java    From OpenCV-android with Apache License 2.0 5 votes vote down vote up
/**
 * 根据屏占比获取大小
 *
 * @param gray                 gray
 * @param relativeObjectWidth  最小宽度屏占比
 * @param relativeObjectHeight 最小高度屏占比
 * @return 大小
 */
private Size getSize(Mat gray, float relativeObjectWidth, float relativeObjectHeight) {
    Size size = gray.size();
    int cameraWidth = gray.cols();
    int cameraHeight = gray.rows();
    int width = Math.round(cameraWidth * relativeObjectWidth);
    int height = Math.round(cameraHeight * relativeObjectHeight);
    size.width = 0 >= width ? 0 : (cameraWidth < width ? cameraWidth : width); // width [0, cameraWidth]
    size.height = 0 >= height ? 0 : (cameraHeight < height ? cameraHeight : height); // height [0, cameraHeight]
    return size;
}
 
Example 12
Source File: SarxosCaptureCamera.java    From ShootOFF with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Frame getFrame() {
	final Mat frame = new Mat();
	try {
		if (!isOpen() || !camera.read(frame) || frame.size().height == 0 || frame.size().width == 0) return null;
	} catch (final Exception e) {
		// Sometimes there is a race condition on closing the camera vs.
		// read()
		return null;
	}

	final long currentFrameTimestamp = System.currentTimeMillis();
	frameCount++;
	return new Frame(frame, currentFrameTimestamp);
}
 
Example 13
Source File: NativeClass.java    From AndroidDocumentScanner with MIT License 4 votes vote down vote up
public List<MatOfPoint2f> getPoints(Mat src) {

        // Blur the image to filter out the noise.
        Mat blurred = new Mat();
        Imgproc.medianBlur(src, blurred, 9);

        // Set up images to use.
        Mat gray0 = new Mat(blurred.size(), CvType.CV_8U);
        Mat gray = new Mat();

        // For Core.mixChannels.
        List<MatOfPoint> contours = new ArrayList<>();
        List<MatOfPoint2f> rectangles = new ArrayList<>();

        List<Mat> sources = new ArrayList<>();
        sources.add(blurred);
        List<Mat> destinations = new ArrayList<>();
        destinations.add(gray0);

        // To filter rectangles by their areas.
        int srcArea = src.rows() * src.cols();

        // Find squares in every color plane of the image.
        for (int c = 0; c < 3; c++) {
            int[] ch = {c, 0};
            MatOfInt fromTo = new MatOfInt(ch);

            Core.mixChannels(sources, destinations, fromTo);

            // Try several threshold levels.
            for (int l = 0; l < THRESHOLD_LEVEL; l++) {
                if (l == 0) {
                    // HACK: Use Canny instead of zero threshold level.
                    // Canny helps to catch squares with gradient shading.
                    // NOTE: No kernel size parameters on Java API.
                    Imgproc.Canny(gray0, gray, 10, 20);

                    // Dilate Canny output to remove potential holes between edge segments.
                    Imgproc.dilate(gray, gray, Mat.ones(new Size(3, 3), 0));
                } else {
                    int threshold = (l + 1) * 255 / THRESHOLD_LEVEL;
                    Imgproc.threshold(gray0, gray, threshold, 255, Imgproc.THRESH_BINARY);
                }

                // Find contours and store them all as a list.
                Imgproc.findContours(gray, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

                for (MatOfPoint contour : contours) {
                    MatOfPoint2f contourFloat = MathUtils.toMatOfPointFloat(contour);
                    double arcLen = Imgproc.arcLength(contourFloat, true) * 0.02;

                    // Approximate polygonal curves.
                    MatOfPoint2f approx = new MatOfPoint2f();
                    Imgproc.approxPolyDP(contourFloat, approx, arcLen, true);

                    if (isRectangle(approx, srcArea)) {
                        rectangles.add(approx);
                    }
                }
            }
        }

        return rectangles;

    }
 
Example 14
Source File: AAVActivity.java    From AAV with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onCameraViewStarted(int width, int height) {
	_rgbaImage = new Mat(height, width, CvType.CV_8UC4);
	_screenCenterCoordinates.x = _rgbaImage.size().width / 2;
	_screenCenterCoordinates.y = _rgbaImage.size().height / 2;
}
 
Example 15
Source File: CVProcessor.java    From CVScanner with GNU General Public License v3.0 4 votes vote down vote up
public static List<MatOfPoint> findContours(Mat src){
    Mat img = src.clone();

    //find contours
    double ratio = getScaleRatio(img.size());
    int width = (int) (img.size().width / ratio);
    int height = (int) (img.size().height / ratio);
    Size newSize = new Size(width, height);
    Mat resizedImg = new Mat(newSize, CvType.CV_8UC4);
    Imgproc.resize(img, resizedImg, newSize);
    img.release();

    Imgproc.medianBlur(resizedImg, resizedImg, 7);

    Mat cannedImg = new Mat(newSize, CvType.CV_8UC1);
    Imgproc.Canny(resizedImg, cannedImg, 70, 200, 3, true);
    resizedImg.release();

    Imgproc.threshold(cannedImg, cannedImg, 70, 255, Imgproc.THRESH_OTSU);

    Mat dilatedImg = new Mat(newSize, CvType.CV_8UC1);
    Mat morph = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(3, 3));
    Imgproc.dilate(cannedImg, dilatedImg, morph, new Point(-1, -1), 2, 1, new Scalar(1));
    cannedImg.release();
    morph.release();

    ArrayList<MatOfPoint> contours = new ArrayList<>();
    Mat hierarchy = new Mat();
    Imgproc.findContours(dilatedImg, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
    hierarchy.release();
    dilatedImg.release();

    Log.d(TAG, "contours found: " + contours.size());

    Collections.sort(contours, new Comparator<MatOfPoint>() {
        @Override
        public int compare(MatOfPoint o1, MatOfPoint o2) {
            return Double.valueOf(Imgproc.contourArea(o2)).compareTo(Imgproc.contourArea(o1));
        }
    });

    return contours;
}
 
Example 16
Source File: LeviColorFilter.java    From DogeCV with GNU General Public License v3.0 4 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) {
    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 17
Source File: ProcessHelper.java    From OpenCV-android with Apache License 2.0 4 votes vote down vote up
/**
 * 直线检测
 *
 * @param origin   原始bitmap
 * @param callback 回调
 */
public void hough(Bitmap origin, ProcessCallback callback) {
    if (origin == null) {
        return;
    }
    try {
        Bitmap bitmap = Bitmap.createBitmap(origin.getWidth(), origin.getHeight(), Bitmap.Config.RGB_565);
        Utils.bitmapToMat(origin, rgbMat);
        Imgproc.cvtColor(rgbMat, grayMat, Imgproc.COLOR_RGB2GRAY);
        Mat edges = new Mat();
        Mat src = new Mat(origin.getHeight(), origin.getWidth(), CvType.CV_8UC4);
        Mat lines = new Mat();
        // 拷贝
        Mat origination = new Mat(src.size(), CvType.CV_8UC1);
        src.copyTo(origination);
        // 通过Canny得到边缘图
        Imgproc.cvtColor(origination, grayMat, Imgproc.COLOR_BGR2GRAY);
        Imgproc.Canny(grayMat, edges, 50, 200);
        // 获取直线图
        Imgproc.HoughLinesP(edges, lines, 1, Math.PI / 180, 10, 0, 10);
        Mat houghLines = new Mat();
        houghLines.create(edges.rows(), edges.cols(), CvType.CV_8UC1);
        // 绘制直线
        for (int i = 0; i < lines.rows(); i++) {
            double[] points = lines.get(i, 0);
            if (null != points) {
                double x1, y1, x2, y2;
                x1 = points[0];
                y1 = points[1];
                x2 = points[2];
                y2 = points[3];
                Point pt1 = new Point(x1, y1);
                Point pt2 = new Point(x2, y2);
                Imgproc.line(houghLines, pt1, pt2, new Scalar(55, 100, 195), 3);
            }
        }
        Utils.matToBitmap(houghLines, bitmap);
        callback.onSuccess(bitmap);
    } catch (Exception e) {
        callback.onFailed(e.getMessage());
    }
}
 
Example 18
Source File: OpticalFlowOp.java    From StormCV with Apache License 2.0 4 votes vote down vote up
@Override
public List<CVParticle> execute(List<CVParticle> input) throws Exception {
	List<CVParticle> result = new ArrayList<CVParticle>();
	if(input.size() != 2 || !(input.get(0) instanceof Frame) || !(input.get(1) instanceof Frame))
		return result;
	
	Frame frame1 = (Frame)input.get(0);
	Frame frame2 = (Frame)input.get(1);
	
	MatOfByte mob1 = new MatOfByte(frame1.getImageBytes());
	Mat image1 = Highgui.imdecode(mob1, Highgui.CV_LOAD_IMAGE_ANYCOLOR);
	Mat image1Gray = new Mat( image1.size(), CvType.CV_8UC1 );
	Imgproc.cvtColor( image1, image1Gray, Imgproc.COLOR_RGB2GRAY );
	
	MatOfByte mob2 = new MatOfByte(frame2.getImageBytes());
	Mat image2 = Highgui.imdecode(mob2, Highgui.CV_LOAD_IMAGE_ANYCOLOR);
	Mat image2Gray = new Mat( image2.size(), CvType.CV_8UC1 );
	Imgproc.cvtColor( image2, image2Gray, Imgproc.COLOR_RGB2GRAY );
	
	Mat opticalFlow = new Mat( image1Gray.size(), CvType.CV_32FC2 );
	Video.calcOpticalFlowFarneback( image1Gray, image2Gray, opticalFlow, 0.5, 1, 1, 1, 7, 1.5, 1 );
	
	int cols = opticalFlow.cols();
	int rows = opticalFlow.rows();
	int maxz = opticalFlow.get(0,0).length;
	float[] tmp = new float[maxz];
	float[][][] dense = new float[cols][rows][maxz];
	for(int y=0; y<opticalFlow.rows(); y++){
		for(int x=0; x<opticalFlow.cols(); x++){
			opticalFlow.get(y,x, tmp);
			dense[x][y][0] = tmp[0];
			dense[x][y][1] = tmp[1];
		}
	}
	
	Feature feature = new Feature(frame1.getStreamId(), frame1.getSequenceNr(), name, frame2.getSequenceNr()-frame1.getSequenceNr(), null, dense);
	if(outputFrame){
		frame1.getFeatures().add(feature);
		result.add(frame1);
	}else{
		result.add(feature);
	}

	return result;
}
 
Example 19
Source File: ImageProcessor.java    From Document-Scanner with GNU General Public License v3.0 3 votes vote down vote up
private boolean detectPreviewDocument(Mat inputRgba) {

        ArrayList<MatOfPoint> contours = findContours(inputRgba);

        Quadrilateral quad = getQuadrilateral(contours, inputRgba.size());

        mPreviewPoints = null;
        mPreviewSize = inputRgba.size();

        if (quad != null) {

            Point[] rescaledPoints = new Point[4];

            double ratio = inputRgba.size().height / 500;

            for ( int i=0; i<4 ; i++ ) {
                int x = Double.valueOf(quad.points[i].x*ratio).intValue();
                int y = Double.valueOf(quad.points[i].y*ratio).intValue();
                if (mBugRotate) {
                    rescaledPoints[(i+2)%4] = new Point( Math.abs(x- mPreviewSize.width), Math.abs(y- mPreviewSize.height));
                } else {
                    rescaledPoints[i] = new Point(x, y);
                }
            }

            mPreviewPoints = rescaledPoints;

            drawDocumentBox(mPreviewPoints, mPreviewSize);

            Log.d(TAG, quad.points[0].toString() + " , " + quad.points[1].toString() + " , " + quad.points[2].toString() + " , " + quad.points[3].toString());

            return true;
        }

        mMainActivity.getHUD().clear();
        mMainActivity.invalidateHUD();

        return false;
    }
 
Example 20
Source File: ImageProcessor.java    From react-native-documentscanner-android with MIT License 2 votes vote down vote up
private boolean detectPreviewDocument(Mat inputRgba) {

        ArrayList<MatOfPoint> contours = findContours(inputRgba);

        Quadrilateral quad = getQuadrilateral(contours, inputRgba.size());

        Log.i("DESENHAR","Quad----->"+quad);

        mPreviewPoints = null;
        mPreviewSize = inputRgba.size();

        if (quad != null) {

            Point[] rescaledPoints = new Point[4];

            double ratio = inputRgba.size().height / 500;


            for ( int i=0; i<4 ; i++ ) {
                int x = Double.valueOf(quad.points[i].x*ratio).intValue();
                int y = Double.valueOf(quad.points[i].y*ratio).intValue();
                if (mBugRotate) {
                    rescaledPoints[(i+2)%4] = new Point( Math.abs(x- mPreviewSize.width), Math.abs(y- mPreviewSize.height));
                } else {
                    rescaledPoints[i] = new Point(x, y);
                }
            }

            mPreviewPoints = rescaledPoints;

            drawDocumentBox(mPreviewPoints, mPreviewSize);

            return true;

        }

        mMainActivity.getHUD().clear();
        mMainActivity.invalidateHUD();

        return false;

    }