Example usage for org.opencv.imgproc Imgproc resize

List of usage examples for org.opencv.imgproc Imgproc resize

Introduction

In this page you can find the example usage for org.opencv.imgproc Imgproc resize.

Prototype

public static void resize(Mat src, Mat dst, Size dsize, double fx, double fy, int interpolation) 

Source Link

Usage

From source file:com.jeremydyer.nifi.ZoomImageProcessor.java

License:Apache License

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile original = session.get();
    if (original == null) {
        return;//  ww  w  . j a va 2 s.  com
    }

    session.transfer(session.clone(original), REL_ORIGINAL);

    FlowFile ff = session.write(original, new StreamCallback() {
        @Override
        public void process(InputStream inputStream, OutputStream outputStream) throws IOException {
            try {
                int zoomingFactor = context.getProperty(ZOOMING_FACTOR).asInteger();

                BufferedImage image = ImageIO.read(inputStream);
                byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
                Mat source = new Mat(image.getHeight(), image.getWidth(), Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE);
                source.put(0, 0, pixels);

                Mat destination = new Mat(source.rows() * zoomingFactor, source.cols() * zoomingFactor,
                        source.type());
                Imgproc.resize(source, destination, destination.size(), zoomingFactor, zoomingFactor,
                        Imgproc.INTER_NEAREST);

                MatOfByte bytemat = new MatOfByte();
                Imgcodecs.imencode(".png", destination, bytemat);
                pixels = bytemat.toArray();
                outputStream.write(pixels);

            } catch (Exception ex) {
                getLogger().error(ex.getMessage());
                ex.printStackTrace();
            }
        }
    });

    session.transfer(ff, REL_SUCCESS);

}

From source file:com.orange.documentare.core.image.opencv.OpenCvImage.java

License:Open Source License

public static Mat resize(Mat mat, int bytesSizeTarget) {
    long matBytesCount = matBytesCount(mat);
    float ratio = (float) matBytesCount / bytesSizeTarget;
    double sqrtRatio = Math.sqrt(ratio);
    int newWidth = (int) (mat.size().width / sqrtRatio);
    int newHeigth = (int) (mat.size().height / sqrtRatio);
    Mat newMat = new Mat(newHeigth, newWidth, mat.type());
    Imgproc.resize(mat, newMat, newMat.size(), sqrtRatio, sqrtRatio, Imgproc.INTER_LANCZOS4);
    return newMat;
}

From source file:com.sikulix.api.Image.java

License:Open Source License

/**
 * resize the image's CV-Mat by factor//from  ww  w.  j ava 2  s . c  o  m
 *
 * @param factor resize factor
 * @return a new inMemory Image
 */
public Image resize(float factor) {
    Image img = new Image();
    if (isValid()) {
        Mat newMat = new Mat();
        Size newS = new Size(w * factor, h * factor);
        Imgproc.resize(content, newMat, newS, 0, 0, Imgproc.INTER_AREA);
        img = new Image(newMat);
    }
    return img;
}

From source file:com.sikulix.api.Picture.java

License:Open Source License

public Mat getResizedMat(double factor) {
    Mat newMat = getContent();//from  ww  w.jav  a 2 s .  c  o  m
    if (isValid()) {
        newMat = new Mat();
        Size newS = new Size(w * factor, h * factor);
        Imgproc.resize(getContent(), newMat, newS, 0, 0, Imgproc.INTER_AREA);
    }
    return newMat;
}

From source file:com.sikulix.core.Finder.java

License:Open Source License

private FindResult doFind(Element elem, FindType findType) {
    if (!elem.isTarget()) {
        return null;
    }/*  w  w w .j a va2  s .c  om*/
    log.trace("doFind: start");
    Element target = elem;
    if (target.getWantedScore() < 0) {
        target.setWantedScore(0.8);
    }
    boolean success = false;
    long begin_t = 0;
    Core.MinMaxLocResult mMinMax = null;
    FindResult findResult = null;
    if (FindType.ONE.equals(findType) && !isCheckLastSeen && SX.isOption("CheckLastSeen")
            && target.getLastSeen().isValid()) {
        begin_t = new Date().getTime();
        Finder lastSeenFinder = new Finder(target.getLastSeen());
        lastSeenFinder.isCheckLastSeen = true;
        target = new Target(target, target.getLastSeen().getScore() - 0.01);
        findResult = lastSeenFinder.doFind(target, FindType.ONE);
        if (findResult.hasNext()) {
            log.trace("doFind: checkLastSeen: success %d msec", new Date().getTime() - begin_t);
            return findResult;
        } else {
            log.trace("doFind: checkLastSeen: not found %d msec", new Date().getTime() - begin_t);
        }
    }
    double rfactor = 0;
    boolean downSizeFound = false;
    double downSizeScore = 0;
    double downSizeWantedScore = 0;
    if (FindType.ONE.equals(findType) && target.getResizeFactor() > resizeMinFactor) {
        // ************************************************* search in downsized
        begin_t = new Date().getTime();
        double imgFactor = target.getResizeFactor();
        Size sb, sp;
        Mat mBase = new Mat(), mPattern = new Mat();
        result = null;
        for (double factor : resizeLevels) {
            rfactor = factor * imgFactor;
            sb = new Size(base.cols() / rfactor, base.rows() / rfactor);
            sp = new Size(target.getContent().cols() / rfactor, target.getContent().rows() / rfactor);
            Imgproc.resize(base, mBase, sb, 0, 0, Imgproc.INTER_AREA);
            Imgproc.resize(target.getContent(), mPattern, sp, 0, 0, Imgproc.INTER_AREA);
            result = doFindMatch(target, mBase, mPattern);
            mMinMax = Core.minMaxLoc(result);
            downSizeWantedScore = ((int) ((target.getWantedScore() - downSimDiff) * 100)) / 100.0;
            downSizeScore = mMinMax.maxVal;
            if (downSizeScore > downSizeWantedScore) {
                downSizeFound = true;
                break;
            }
        }
        log.trace("doFind: down: %%%.2f %d msec", 100 * mMinMax.maxVal, new Date().getTime() - begin_t);
    }
    if (FindType.ONE.equals(findType) && downSizeFound) {
        // ************************************* check after downsized success
        if (base.size().equals(target.getContent().size())) {
            // trust downsized result, if images have same size
            return new FindResult(result, target);
        } else {
            int maxLocX = (int) (mMinMax.maxLoc.x * rfactor);
            int maxLocY = (int) (mMinMax.maxLoc.y * rfactor);
            begin_t = new Date().getTime();
            int margin = ((int) target.getResizeFactor()) + 1;
            Rect rectSub = new Rect(Math.max(0, maxLocX - margin), Math.max(0, maxLocY - margin),
                    Math.min(target.w + 2 * margin, base.width()),
                    Math.min(target.h + 2 * margin, base.height()));
            result = doFindMatch(target, base.submat(rectSub), null);
            mMinMax = Core.minMaxLoc(result);
            if (mMinMax.maxVal > target.getWantedScore()) {
                findResult = new FindResult(result, target, new int[] { rectSub.x, rectSub.y });
            }
            if (SX.isNotNull(findResult)) {
                log.trace("doFind: after down: %%%.2f(?%%%.2f) %d msec", mMinMax.maxVal * 100,
                        target.getWantedScore() * 100, new Date().getTime() - begin_t);
            }
        }
    }
    // ************************************** search in original
    if (((int) (100 * downSizeScore)) == 0) {
        begin_t = new Date().getTime();
        result = doFindMatch(target, base, null);
        mMinMax = Core.minMaxLoc(result);
        if (!isCheckLastSeen) {
            log.trace("doFind: search in original: %d msec", new Date().getTime() - begin_t);
        }
        if (mMinMax.maxVal > target.getWantedScore()) {
            findResult = new FindResult(result, target);
        }
    }
    log.trace("doFind: end");
    return findResult;
}

From source file:cpsd.ImageGUI.java

private void zoomImage(double zoomlevel) {
    Mat source = ImageClass.getInstance().getImage();
    Mat destination = new Mat((int) (source.rows() * zoomlevel), (int) (source.cols() * zoomlevel),
            source.type());//from   www. j a v a2s .  com
    Imgproc.resize(source, destination, destination.size(), zoomlevel, zoomlevel, INTER_CUBIC);
    ImageClass.getInstance().setImage(destination);
    zoomSlider.setValue((int) (zoomlevel * 10));
}

From source file:edu.fiu.cate.breader.BaseSegmentation.java

/**
 * Capture button has been press. Obtain the high resolution image and the low resolution 
 * data. Once captured, the images are corrected. 
 *///ww  w. jav a2s.  c  om
public void captureEvent() {
    long t0, t1;
    t0 = System.currentTimeMillis();
    t1 = t0;
    byte[][][] img = getHidefImage();
    System.out.println("HiRez Capture: " + (System.currentTimeMillis() - t0) / 1000.0);
    new IViewer("HiRez", ImageManipulation.getBufferedImage(img));

    t0 = System.currentTimeMillis();
    Rect bound = null;
    try {
        bound = highRes(BReaderTools.byteArrayToMat(ITools.toGrayscale(img)));
    } catch (java.lang.Exception e) {
    }
    System.out.println("First bounding box: " + (System.currentTimeMillis() - t0) / 1000.0);

    //      Mat imgMat = BReaderTools.byteArrayToMat(img);
    //      Imgproc.rectangle(imgMat, bound.tl(), bound.br(), new Scalar(255,255,0), 8);

    byte[][] low = ITools.normalize(normImgCropped);
    t0 = System.currentTimeMillis();
    Rect boundLow = null;
    try {
        boundLow = lowResDist(BReaderTools.byteArrayToMat(low));
    } catch (java.lang.Exception e) {
    }
    System.out.println("second bounding box: " + (System.currentTimeMillis() - t0) / 1000.0);

    if (bound == null || boundLow == null) {
        tts.doTTS("Document outside field of view. Please realign and press capture again.");
        return;
    }

    if ((bound.x + bound.width + 100) >= img[0][0].length || (bound.y + bound.height + 100) >= img[0].length) {
        tts.doTTS("Document outside field of view. Please realign and press capture again.");
        return;
    }

    //Show the cropped height map with the bounding box
    Mat color = new Mat();
    Imgproc.cvtColor(BReaderTools.byteArrayToMat(low), color, Imgproc.COLOR_GRAY2BGR);
    Imgproc.rectangle(color, boundLow.tl(), boundLow.br(), new Scalar(255, 255, 0), 1);
    new IViewer("LowRes Bounding Box", BReaderTools.bufferedImageFromMat(color));

    Imgproc.cvtColor(BReaderTools.byteArrayToMat(ITools.toGrayscale(img)), color, Imgproc.COLOR_GRAY2BGR);
    Imgproc.rectangle(color, bound.tl(), bound.br(), new Scalar(255, 255, 0), 8);
    new IViewer("HighRes Bounding Box", BReaderTools.bufferedImageFromMat(color));

    //      System.out.println(bound.height+", "+bound.width+": "+(double)bound.width/(double)bound.height);
    //      System.out.println(boundLow.height+", "+boundLow.width+": "+(double)boundLow.width/(double)boundLow.height);

    double rW = (double) bound.width / (double) boundLow.width;
    double rH = (double) bound.height / (double) boundLow.height;
    int h = 0, w = 0, yO = 0, xO = 0;
    double s = 0;

    if (rH < rW) {
        s = rH;
        h = boundLow.height;
        w = (int) (bound.width / rH);
        if ((w - boundLow.width) % 2 == 0) {
            xO = (boundLow.width - w) / 2;
        }
    } else {
        s = rW;
        h = (int) (bound.height / rW);
        w = boundLow.width;
        if ((h - boundLow.height) % 2 == 0) {
            yO = (boundLow.height - h) / 2;
        }
    }

    //show the high resolution image cropped
    byte[][][] hiRez = new byte[img.length][][];
    t0 = System.currentTimeMillis();
    for (int i = 0; i < img.length; i++) {
        hiRez[i] = ITools.crop(bound.x, bound.y, bound.x + bound.width, bound.y + bound.height, img[i]);
    }
    System.out.println("Cropping HiRez: " + (System.currentTimeMillis() - t0) / 1000.0);

    //Show the IR amplitude image cropped
    //      byte[][] amp = ITools.normalize(amplitudes);
    //      byte[][] ampRez = resize(amp, (float)s);
    //      int x0 = (int) ((boundLow.x+xO+40)*s), y0 = (int) ((boundLow.y+yO+25)*s);
    //      ampRez = ITools.crop(x0, y0, x0+bound.width, y0+bound.height, ampRez);
    //      new IViewer(ImageManipulation.getGrayBufferedImage(ampRez));

    //Show the Amplitude image in bounding box
    //      Rect nBound = new Rect(boundLow.x+xO+40, boundLow.y+yO+25, w, h);
    //      Mat gray = new Mat();
    //      Imgproc.cvtColor(BReaderTools.byteArrayToMat(ITools.normalize(amplitudes)), gray,Imgproc.COLOR_GRAY2BGR);
    //      Imgproc.rectangle(gray, nBound.tl(), nBound.br(), new Scalar(255,255,0), 1);
    //      new IViewer(BReaderTools.bufferedImageFromMat(gray));

    //Crop the distance image and prepare for correction
    float[][] distRez;
    Mat destRezM = new Mat();
    switch (disp.getInterpolationMethod()) {
    case 1:
        Imgproc.resize(BReaderTools.floatArrayToMat(normImg), destRezM, new Size(0, 0), s, s,
                Imgproc.INTER_LINEAR);//resize image
        break;
    case 2:
        Imgproc.resize(BReaderTools.floatArrayToMat(normImg), destRezM, new Size(0, 0), s, s,
                Imgproc.INTER_CUBIC);//resize image
        break;
    case 3:
        Imgproc.resize(BReaderTools.floatArrayToMat(normImg), destRezM, new Size(0, 0), s, s,
                Imgproc.INTER_LANCZOS4);//resize image
        break;
    }
    distRez = BReaderTools.matToFloatArray(destRezM);
    int xCentOff = (img[0][0].length - bound.width) / 2 - bound.x;
    int yCentOff = (img[0].length - bound.height) / 2 - bound.y;
    int x0 = (int) ((boundLow.x + xO + 40) * s), y0 = (int) ((boundLow.y + yO + 25) * s);
    distRez = ITools.crop(x0, y0, x0 + bound.width, y0 + bound.height, distRez);
    distRez = multiply(distRez, -100);

    byte[][][] foldCorrected = new byte[hiRez.length][][];
    t0 = System.currentTimeMillis();
    for (int i = 0; i < hiRez.length; i++) {
        foldCorrected[i] = BReaderTools.foldCorrection(hiRez[i], distRez, xCentOff, yCentOff);
    }
    System.out.println("Fold Correction: " + (System.currentTimeMillis() - t0) / 1000.0);

    float[][] distRezPushed = BReaderTools.foldCorrection(distRez,
            (distRez[0].length - boundLow.width) / 2 - boundLow.x,
            (distRez.length - boundLow.height) / 2 - boundLow.y);

    byte[][][] extensionCorrected = new byte[hiRez.length][][];
    t0 = System.currentTimeMillis();
    for (int i = 0; i < hiRez.length; i++) {
        extensionCorrected[i] = LuWang.extentionWithLinearInterpolation(foldCorrected[i], distRez);
    }
    System.out.println("Extension Correction: " + (System.currentTimeMillis() - t0) / 1000.0);

    new IViewer("Heigths", ImageManipulation.getGrayBufferedImage(ITools.normalize(distRez)));
    new IViewer("HiRez", ImageManipulation.getBufferedImage(hiRez));
    //      new IViewer("Corrected",ImageManipulation.getBufferedImage(foldCorrected));
    //      new IViewer("Heigths",ImageManipulation.getGrayBufferedImage(ITools.normalize(distRezPushed)));
    //      new IViewer("Flat",ImageManipulation.getBufferedImage(foldCorrected));
    //      new IViewer("Extension",ImageManipulation.getBufferedImage(extensionCorrected));
    System.out.println("Overall time: " + (System.currentTimeMillis() - t1) / 1000.0);

    SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd-hh-mm-ss");
    String time = format.format(new Date(System.currentTimeMillis()));

    // Save Corrected High Rez.
    String imgPath = saveDir + "/correctedImage-" + time + ".tiff";
    switch (disp.getCorrectionMethod()) {
    case 1: {
        ImageManipulation.writeImage(hiRez, imgPath);
        new IViewer("Correction Results: None", ImageManipulation.getBufferedImage(hiRez));
    }
        break;
    case 2: {
        ImageManipulation.writeImage(foldCorrected, imgPath);
        new IViewer("Correction Results: Flattening", ImageManipulation.getBufferedImage(foldCorrected));
    }
        break;
    case 3: {
        ImageManipulation.writeImage(extensionCorrected, imgPath);
        new IViewer("Correction Results: Flattening + Extension",
                ImageManipulation.getBufferedImage(extensionCorrected));
    }
        break;
    }

    try {
        String text = abbyy.processImage(imgPath, saveDir + "/text-" + time + ".txt");
        System.out.println("Done!!!!");
        tts.doTTS(text);
    } catch (java.lang.NullPointerException e) {
        tts.doTTS("ABBYY License expired.");
    }
    saveData(time, img, hiRez, distRez, boundLow, bound);

}

From source file:karthik.Barcode.Barcode.java

License:Open Source License

public static boolean updateImage(Barcode barcode, Mat img) {
    // used for video or camera feed when all images are the same size
    int orig_rows = barcode.img_details.src_original.rows();
    int orig_cols = barcode.img_details.src_original.cols();

    int new_rows = img.rows();
    int new_cols = img.cols();

    if ((orig_rows != new_rows) || (orig_cols != new_cols))
        return false;

    barcode.candidateBarcodes.clear();/*from www . j  a  v a 2  s .c  om*/
    barcode.img_details.src_original = img;
    Imgproc.resize(barcode.img_details.src_original, barcode.img_details.src_scaled,
            barcode.img_details.src_scaled.size(), 0, 0, Imgproc.INTER_AREA);
    Imgproc.cvtColor(barcode.img_details.src_scaled, barcode.img_details.src_grayscale, Imgproc.COLOR_RGB2GRAY);

    return true;
}

From source file:karthik.Barcode.Barcode.java

License:Open Source License

protected void preprocess_image() {
    // pre-process image to convert to grayscale and do morph black hat
    // also resizes image if it is above a specified size and sets the search parameters
    // based on image size

    // shrink image if it is above a certain size   
    // it reduces image size for large images which helps with processing speed
    // and reducing sensitivity to barcode size within the image
    if (rows > searchParams.MAX_ROWS) {
        cols = (int) (cols * (searchParams.MAX_ROWS * 1.0 / rows));
        rows = searchParams.MAX_ROWS;//from ww w  .  j a v a 2 s .com
        img_details.src_scaled = new Mat(rows, cols, CvType.CV_32F);
        Imgproc.resize(img_details.src_original, img_details.src_scaled, img_details.src_scaled.size(), 0, 0,
                Imgproc.INTER_AREA);
    }
    if (img_details.src_scaled == null)
        img_details.src_scaled = img_details.src_original.clone();

    searchParams.setImageSpecificParameters(rows, cols);
    // do pre-processing to increase contrast
    img_details.initializeMats(rows, cols, searchParams);

    Imgproc.cvtColor(img_details.src_scaled, img_details.src_grayscale, Imgproc.COLOR_RGB2GRAY);
}

From source file:karthik.Barcode.Barcode.java

License:Open Source License

protected Mat scale_candidateBarcode(Mat candidate) {
    // resizes candidate image to have at least MIN_COLS columns and MIN_ROWS rows
    // called when RESIZE_BEFORE_DECODE is set - seems to help ZXing decode barcode

    int MIN_COLS = 200;
    int MIN_ROWS = 200;

    int num_rows = candidate.rows();
    int num_cols = candidate.cols();

    if ((num_cols > MIN_COLS) && (num_rows > MIN_ROWS))
        return candidate;

    if (num_cols < MIN_COLS) {
        num_rows = (int) (num_rows * MIN_COLS / (1.0 * num_cols));
        num_cols = MIN_COLS;//w  w w  .  ja  va2 s .c om
    }

    if (num_rows < MIN_ROWS) {
        num_cols = (int) (num_cols * MIN_ROWS / (1.0 * num_rows));
        num_rows = MIN_ROWS;
    }

    Mat result = Mat.zeros(num_rows, num_cols, candidate.type());

    Imgproc.resize(candidate, result, result.size(), 0, 0, Imgproc.INTER_CUBIC);
    return result;
}