List of usage examples for org.opencv.core Mat submat
public Mat submat(int rowStart, int rowEnd, int colStart, int colEnd)
From source file:com.trandi.opentld.TLDView.java
License:Apache License
@Override public Mat onCameraFrame(Mat originalFrame) { try {/*from w w w . j a v a2 s.com*/ // Image is too big and this requires too much CPU for a phone, so scale everything down... Imgproc.resize(originalFrame, _workingFrame, WORKING_FRAME_SIZE); final Size workingRatio = new Size(originalFrame.width() / WORKING_FRAME_SIZE.width, originalFrame.height() / WORKING_FRAME_SIZE.height); // usefull to see what we're actually working with... _workingFrame.copyTo(originalFrame.submat(originalFrame.rows() - _workingFrame.rows(), originalFrame.rows(), 0, _workingFrame.cols())); if (_trackedBox != null) { if (_tld == null) { // run the 1st time only Imgproc.cvtColor(_workingFrame, _lastGray, Imgproc.COLOR_RGB2GRAY); _tld = new Tld(_tldProperties); final Rect scaledDownTrackedBox = scaleDown(_trackedBox, workingRatio); Log.i(Util.TAG, "Working Ration: " + workingRatio + " / Tracking Box: " + _trackedBox + " / Scaled down to: " + scaledDownTrackedBox); try { _tld.init(_lastGray, scaledDownTrackedBox); } catch (Exception eInit) { // start from scratch, you have to select an init box again ! _trackedBox = null; _tld = null; throw eInit; // re-throw it as it will be dealt with later } } else { Imgproc.cvtColor(_workingFrame, _currentGray, Imgproc.COLOR_RGB2GRAY); _processFrameStruct = _tld.processFrame(_lastGray, _currentGray); drawPoints(originalFrame, _processFrameStruct.lastPoints, workingRatio, new Scalar(255, 0, 0)); drawPoints(originalFrame, _processFrameStruct.currentPoints, workingRatio, new Scalar(0, 255, 0)); drawBox(originalFrame, scaleUp(_processFrameStruct.currentBBox, workingRatio), new Scalar(0, 0, 255)); _currentGray.copyTo(_lastGray); // overlay the current positive examples on the real image(needs converting at the same time !) //copyTo(_tld.getPPatterns(), originalFrame); } } } catch (Exception e) { _errMessage = e.getClass().getSimpleName() + " / " + e.getMessage(); Log.e(Util.TAG, "TLDView PROBLEM", e); } if (_errMessage != null) { Imgproc.putText(originalFrame, _errMessage, new Point(0, 300), Core.FONT_HERSHEY_PLAIN, 1.3d, new Scalar(255, 0, 0), 2); } return originalFrame; }
From source file:com.trandi.opentld.TLDView.java
License:Apache License
private static void copyTo(List<Mat> patterns, Mat dest) { if (patterns == null || patterns.isEmpty() || dest == null) return;/* ww w. java 2 s . c om*/ final int patternRows = patterns.get(0).rows(); final int patternCols = patterns.get(0).cols(); final int vertCount = dest.rows() / patternRows; final int horizCount = patterns.size() / vertCount + 1; int patchIdx = 0; for (int col = dest.cols() - horizCount * patternCols - 1; col < dest.cols() && patchIdx < patterns.size(); col += patternCols) { for (int row = 0; row < dest.rows() && patchIdx < patterns.size(); row += patternRows) { Imgproc.cvtColor(patterns.get(patchIdx), dest.submat(row, row + patternRows, col, col + patternCols), Imgproc.COLOR_GRAY2RGBA); patchIdx++; } } }
From source file:com.wallerlab.processing.tasks.ComputeRefocusTask.java
License:BSD License
private Bitmap[] computeFocus(float z) { int width = mDataset.WIDTH - 2 * mDataset.XCROP; int height = mDataset.HEIGHT - 2 * mDataset.YCROP; Mat result = new Mat(height, width, CvType.CV_32FC4); Mat result8 = new Mat(height, width, CvType.CV_8UC4); Mat dpc_result_tb = new Mat(height, width, CvType.CV_32FC4); Mat dpc_result_tb8 = new Mat(height, width, CvType.CV_8UC4); Mat dpc_result_lr = new Mat(height, width, CvType.CV_32FC4); Mat dpc_result_lr8 = new Mat(height, width, CvType.CV_8UC4); Mat img; Mat img32 = new Mat(height, width, CvType.CV_32FC4); Mat shifted;//from ww w .ja va 2 s. c o m for (int idx = 0; idx < mDataset.fileCount; idx++) { img = ImageUtils.toMat(BitmapFactory.decodeByteArray(fileByteList[idx], 0, fileByteList[idx].length)); img = img.submat(mDataset.YCROP, mDataset.HEIGHT - mDataset.YCROP, mDataset.XCROP, mDataset.WIDTH - mDataset.XCROP); img.convertTo(img32, result.type()); // Grab actual hole number from filename String fName = mDataset.fileList[idx].toString(); String hNum = fName.substring(fName.indexOf("_scanning_") + 10, fName.indexOf(".jpeg")); int holeNum = Integer.parseInt(hNum); //Log.d(TAG,String.format("BF Scan Header is: %s", hNum)); // Calculate these based on array coordinates int xShift = (int) Math.round(z * tanh_lit[holeNum]); int yShift = (int) Math.round(z * tanv_lit[holeNum]); shifted = ImageUtils.circularShift(img32, yShift, xShift); if (mDataset.leftList.contains(holeNum)) //add LHS { Core.add(dpc_result_lr, shifted, dpc_result_lr); } else //subtract RHS { Core.subtract(dpc_result_lr, shifted, dpc_result_lr); } if (mDataset.topList.contains(holeNum)) //add Top { Core.add(dpc_result_tb, shifted, dpc_result_tb); } else //subtract bottom { Core.subtract(dpc_result_tb, shifted, dpc_result_tb); } Core.add(result, shifted, result); float progress = ((idx + 1) / (float) mDataset.fileCount); onProgressUpdate((int) (progress * 100), -1); Log.d(TAG, String.format("progress: %f", progress)); } Core.MinMaxLocResult minMaxLocResult1 = Core.minMaxLoc(result.reshape(1)); result.convertTo(result8, CvType.CV_8UC4, 255 / minMaxLocResult1.maxVal); Core.MinMaxLocResult minMaxLocResult2 = Core.minMaxLoc(dpc_result_lr.reshape(1)); dpc_result_lr.convertTo(dpc_result_lr8, CvType.CV_8UC4, 255 / (minMaxLocResult2.maxVal - minMaxLocResult2.minVal), -minMaxLocResult2.minVal * 255.0 / (minMaxLocResult2.maxVal - minMaxLocResult2.minVal)); Core.MinMaxLocResult minMaxLocResult3 = Core.minMaxLoc(dpc_result_tb.reshape(1)); dpc_result_tb.convertTo(dpc_result_tb8, CvType.CV_8UC4, 255 / (minMaxLocResult3.maxVal - minMaxLocResult3.minVal), -minMaxLocResult3.minVal * 255.0 / (minMaxLocResult3.maxVal - minMaxLocResult3.minVal)); /* Log.d(TAG,String.format("result_min: %f, max: %f",minMaxLocResult1.minVal,minMaxLocResult1.maxVal)); Log.d(TAG,String.format("lr_min: %f, max: %f",minMaxLocResult2.minVal,minMaxLocResult2.maxVal)); Log.d(TAG,String.format("tb_min: %f, max: %f",minMaxLocResult3.minVal,minMaxLocResult3.maxVal)); */ // remove transparency in DPC images Scalar alphaMask = new Scalar(new double[] { 1.0, 1.0, 1.0, 255.0 }); Core.multiply(dpc_result_lr8, alphaMask, dpc_result_lr8); Core.multiply(dpc_result_tb8, alphaMask, dpc_result_tb8); if (!mDataset.USE_COLOR_DPC) { Imgproc.cvtColor(dpc_result_lr8, dpc_result_lr8, Imgproc.COLOR_BGR2GRAY); Imgproc.cvtColor(dpc_result_tb8, dpc_result_tb8, Imgproc.COLOR_BGR2GRAY); } /* // Cut off edges in DPC images Point centerPt = new Point(); centerPt.x = Math.round((float)width/2.0); centerPt.y = Math.round((float)height/2.0); Mat circleMat = new Mat(dpc_result_lr8.size(), dpc_result_lr8.type()); Scalar color = new Scalar(255); Core.circle(circleMat, centerPt, 200, color); //Core.bitwise_and(circleMat, dpc_result_lr8, dpc_result_lr8); //Core.bitwise_and(circleMat, dpc_result_tb8, dpc_result_tb8); * * */ Bitmap[] outputBitmaps = new Bitmap[3]; outputBitmaps[0] = ImageUtils.toBitmap(result8); outputBitmaps[1] = ImageUtils.toBitmap(dpc_result_lr8); outputBitmaps[2] = ImageUtils.toBitmap(dpc_result_tb8); return outputBitmaps; }
From source file:com.wallerlab.processing.utilities.ImageUtils.java
License:BSD License
public static Mat circularShift(Mat mat, int x, int y) { int w = mat.cols(); int h = mat.rows(); Mat result = Mat.zeros(h, w, CvType.CV_32FC4); int shiftR = x % w; int shiftD = y % h; //java modulus gives negative results for negative numbers if (shiftR < 0) shiftR += w;//from w ww . j av a 2 s.com if (shiftD < 0) shiftD += h; /* extract 4 submatrices |---| shiftR ______________ | | | | 1 | 2 | |_________|___| ___ shiftD | | | | | 3 | 4 | | | | | | |_________|___| _|_ */ Mat shift1 = mat.submat(0, h - shiftD, 0, w - shiftR); Mat shift2 = mat.submat(0, h - shiftD, w - shiftR, w); Mat shift3 = mat.submat(h - shiftD, h, 0, w - shiftR); Mat shift4 = mat.submat(h - shiftD, h, w - shiftR, w); /* and rearrange ______________ | | | | 4 | 3 | | | | |___|_________| | | | | 2 | 1 | |___|_________| */ shift1.copyTo(new Mat(result, new Rect(shiftR, shiftD, w - shiftR, h - shiftD))); shift2.copyTo(new Mat(result, new Rect(0, shiftD, shiftR, h - shiftD))); shift3.copyTo(new Mat(result, new Rect(shiftR, 0, w - shiftR, shiftD))); shift4.copyTo(new Mat(result, new Rect(0, 0, shiftR, shiftD))); return result; }
From source file:cx.uni.jk.mms.iaip.tools.SimpleBrushTool.java
License:Open Source License
@Override public Rect apply(Mat mat, BrushModel brush, int x, int y, boolean inverseEffect) { Rect changedArea = null;/*ww w. jav a2s .c o m*/ try { this.logger.finer(String.format("apply mode=\"%s\" inverse=%s, size=%d, strength=%d", brush.getMode(), inverseEffect, brush.getSize(), brush.getValue())); this.logger.finest("mat = " + mat.toString()); /** where is brush going to work? this may reach outside the mat! */ int brushColStart = x - (brush.getSize() - 1) / 2; int brushColEnd = x + brush.getSize() / 2; int brushRowStart = y - (brush.getSize() - 1) / 2; int brushRowEnd = y + brush.getSize() / 2; if (brushColEnd >= 0 && brushColStart < mat.cols() && brushRowEnd >= 0 && brushRowStart < mat.rows()) { /** calculate bounds for roiMat to fit into original mat */ int subColStart = Math.max(0, brushColStart); int subColEnd = Math.min(brushColEnd, mat.cols() - 1); int subRowStart = Math.max(0, brushRowStart); int subRowEnd = Math.min(brushRowEnd, mat.rows() - 1); /** * the caller may want to know. Rect constructor interprets the * second point being outside of the Rect! a one pixel rectangle * Rect(Point(a,b), Point(a+1,b+1)) has height and width 1. see * * @link{http://docs.opencv.org/java/org/opencv/core/Rect.html */ changedArea = new Rect(new Point(subColStart, subRowStart), new Point(subColEnd + 1, subRowEnd + 1)); /** * get the part of original mat which going to be affected by * change */ Mat roiMat = mat.submat(subRowStart, subRowEnd + 1, subColStart, subColEnd + 1); this.logger.finest("matRoi = " + roiMat.toString()); /** does the brush fit into the roiMat we shall work on ? */ boolean brushFits = brushColStart == subColStart && brushColEnd == subColEnd && brushRowStart == subRowStart && brushRowEnd == subRowEnd; this.logger.finest("brush fits = " + brushFits); /** * make sure to have a working mat which matches the full brush * size */ Mat workMat, workRoi = null; if (brushFits) { /** just work in the original mat area defined by roi */ workMat = roiMat; } else { /** create a new mat as big as the brush */ workMat = Mat.zeros(brush.getSize(), brush.getSize(), MatModel.MAT_TYPE); this.logger.finest("workMat= " + workMat.toString()); /** * create an ROI in the workMat as big as the subMat, * correct offset for brushing in the middle */ int roiColStart = subColStart - brushColStart; int roiColEnd = roiColStart + roiMat.cols(); int roiRowStart = subRowStart - brushRowStart; int roiRowEend = roiRowStart + roiMat.rows(); workRoi = workMat.submat(roiRowStart, roiRowEend, roiColStart, roiColEnd); this.logger.finest("workRoi= " + workRoi.toString()); roiMat.copyTo(workRoi); this.logger.finest("workRoi= " + workRoi.toString()); // workRoi.put(0, 0, 1333.0d); this.logger.finest("roiMat dump1 " + roiMat.dump()); this.logger.finest("workRoi dump1 " + workRoi.dump()); this.logger.finest("workMat dump1 " + workMat.dump()); } /** the real action */ this.applyToWorkMat(brush, inverseEffect, workMat); this.logger.finest("workMat dump2 " + workMat.dump()); this.logger.finest("matRoi dump2 " + roiMat.dump()); if (brushFits) { /** * nothing to do, we have been working directly in original * mat */ } else { /** copy workMat back into original mat */ this.logger.finest("workRoi dump2 " + workRoi.dump()); // workRoi.put(0, 0, 1338); this.logger.finest("workRoi dump3 " + workRoi.dump()); /** * copy roi of changed workmat back into roi of original mat */ this.logger.finest("matRoi = " + roiMat.toString()); workRoi.copyTo(roiMat); this.logger.finest("matRoi = " + roiMat.toString()); } this.logger.finest("matRoi dump3 " + roiMat.dump()); } } catch (CvException e) { /** nevermind if the user does not notice */ this.logger.fine(e.getStackTrace().toString()); } /** let the caller know caller which area has potentially been changed */ return changedArea; }
From source file:edu.sust.cse.detection.algorithm.ImageBorderDetectionBFS.java
private void categorize(BorderItem item, Mat m2) { Mat subMat2 = m2.submat(item.getMinX(), item.getMaxX(), item.getMinY(), item.getMaxY()); ImageDetection isImage = new ImageDetection(); if (isImage.isImage(subMat2)) { Mat subMat = m1.submat(item.getMinX(), item.getMaxX(), item.getMinY(), item.getMaxY()); item.setIsImage(true);/*from ww w. j a v a 2 s. co m*/ item.setBlock(subMat); imageItems.add(item); borderItems.add(item); } else { otherItems.add(item); } }
From source file:edu.sust.cse.detection.algorithm.ImageBorderDetectionBFS.java
private void eraseImges() { Mat mLocal = ImageBorderDetectionBFS.m1.clone(); for (BorderItem imageItem : imageItems) { int iMinX = imageItem.getMinX(), iMinY = imageItem.getMinY(), iMaxX = imageItem.getMaxX(), iMaxY = imageItem.getMaxY(); double[] data = null; for (int i = iMinX; i < iMaxX; i++) { for (int j = iMinY; j < iMaxY; j++) { data = mLocal.get(i, j); data[0] = 255.0;/* www . j a va2s. c o m*/ data[1] = 255.0; data[2] = 255.0; mLocal.put(i, j, data); } } } NewsAnalysis.imshow("img_removed", mLocal); // return; for (int i = 0; i < otherItems.size(); i++) { BorderItem otherItem = otherItems.get(i); Mat subMat = mLocal.submat(otherItem.getMinX(), otherItem.getMaxX(), otherItem.getMinY(), otherItem.getMaxY()); otherItem.setBlock(subMat); otherItems.set(i, otherItem); borderItems.add(otherItem); } }
From source file:es.ugr.osgiliart.drawer.OpenCVCollageDrawer.java
License:Open Source License
@Override public void draw(ArtisticIndividual artistic) { /*// ww w . j a v a 2 s . c om * */ int imageWidth = (Integer) this.getAlgorithmParameters().getParameter(ArtisticParameters.IMAGE_WIDTH); int imageHeight = (Integer) this.getAlgorithmParameters().getParameter(ArtisticParameters.IMAGE_HEIGHT); String imageType = (String) this.getAlgorithmParameters().getParameter(ArtisticParameters.IMAGE_TYPE); String folderPath = (String) this.getAlgorithmParameters().getParameter(ArtisticParameters.DATA_FOLDER); List<Primitive> primitives = ((ArtisticGenome) artistic.getGenome()).getPrimitives(); Mat orig = new Mat(imageWidth, imageHeight, CvType.CV_8UC3, new Scalar(255, 255, 255)); for (Primitive p : primitives) { Patch patch = (Patch) p; Mat pm = patch.getMat(); int posCol = (int) (patch.getLocation().x * orig.cols()); int posRow = (int) (patch.getLocation().y * orig.rows()); int finalCol = posCol + pm.cols(); int finalRow = posRow + pm.rows(); if (finalCol > orig.cols()) finalCol = orig.cols(); if (finalRow > orig.rows()) finalRow = orig.rows(); //System.out.println("Poniendo imagen de tamao "+pm.rows()+","+pm.cols()+" en "+posRow+","+posCol+" hasta "+finalRow+","+finalCol); Mat bSubmat = orig.submat(posRow, finalRow, posCol, finalCol); pm.copyTo(bSubmat); } /* * draw image ****************************************************/ /*save image */ String imageExtension = null; if (imageType.equalsIgnoreCase(IMAGE_TYPE_JPEG)) { imageExtension = "jpg"; } else if (imageType.equalsIgnoreCase(IMAGE_TYPE_PNG)) { imageExtension = "png"; } if (imageExtension != null) { String imagePath = String.format("%s/%s.%s", folderPath, artistic.getId(), imageExtension); //System.out.println("Saving... " + imagePath + " primitives: " + primitives.size()); //graphics.save(imagePath); //applet.save(imagePath); Highgui.imwrite(imagePath, orig); artistic.setImagePath(imagePath); } }
From source file:news_analysis.isimage.IsImage.java
public boolean isImage(Mat image) { Size imageSize = image.size();//from w w w . java 2 s . c o m int width = image.width(); int height = image.height(); borderDetection = new BorderDetection(); ArrayList<BorderItem> borderItems = borderDetection.getBorder(image, width, height); Mat[] subMat = new Mat[borderItems.size()]; for (int i = 0; i < borderItems.size(); i++) { BorderItem item = borderItems.get(i); if (item.getHeight() > 100 && item.getWidth() > 100) { item = canMaxiMizeBorder(item, item.getMinX(), item.getMaxX(), item.getMinY(), item.getMaxY(), height, width); subMat[i] = image.submat(item.getMinX(), item.getMaxX(), item.getMinY(), item.getMaxY()); //NewsAnalysis.imshow("Sub sub sub" + i, subMat[i]); int horizontal[] = horizontalChecked(subMat[i], item.getHeight() - 1, item.getWidth() - 1); int verticle[] = VerticleChecked(subMat[i], item.getHeight() - 1, item.getWidth() - 1); if (horizontal[0] + horizontal[1] > 110 && verticle[0] + verticle[1] > 110) { return true; } return true; } } return false; }
From source file:news_analysis.NewsAnalysis.java
public static void main(String[] args) throws IOException { file = new File("F:\\AbcFile\\filename.txt"); if (!file.exists()) { file.createNewFile();// w w w .j a v a2s . c o m } fw = new FileWriter(file.getAbsoluteFile()); bw = new BufferedWriter(fw); bw.flush(); // Load an image file and display it in a window. Mat m1 = Highgui.imread("E:\\Raw Java Project\\Thesis\\test6.jpg"); //imshow("Original", m1); // Do some image processing on the image and display in another window. Mat m2 = new Mat(); Imgproc.bilateralFilter(m1, m2, -1, 50, 10); Imgproc.Canny(m2, m2, 10, 200); imshow("Edge Detected", m2); Size sizeA = m2.size(); System.out.println("width: " + sizeA.width + " Height: " + sizeA.height); int width = (int) sizeA.width; int hight = (int) sizeA.height; int pointLength[][][] = new int[hight][width][2]; for (int i = 0; i < hight; i++) { for (int j = 0; j < width; j++) { double[] data = m2.get(i, j); if (m2.get(i, j)[0] != 0) { pointLength[i][j][0] = 0; pointLength[i][j][1] = 0; continue; } if (j != 0 && m2.get(i, j - 1)[0] == 0) { pointLength[i][j][0] = pointLength[i][j - 1][0]; } else { int count = 0; for (int k = j + 1; k < width; k++) { if (m2.get(i, k)[0] == 0) { count++; } else { break; } } pointLength[i][j][0] = count; } if (i != 0 && m2.get(i - 1, j)[0] == 0) { pointLength[i][j][1] = pointLength[i - 1][j][1]; } else { int count = 0; for (int k = i + 1; k < hight; k++) { if (m2.get(k, j)[0] == 0) { count++; } else { break; } } pointLength[i][j][1] = count; } //System.out.println(data[0]); } } String temp = ""; Mat convertArea = m2.clone(); int[][] balckWhite = new int[hight][width]; for (int i = 0; i < hight; i++) { temp = ""; for (int j = 0; j < width; j++) { if (i == 0 || j == 0 || i == hight - 1 || j == width - 1) { temp = temp + "@"; balckWhite[i][j] = 1; double[] data = m2.get(i, j); data[0] = 255.0; convertArea.put(i, j, data); } else if (pointLength[i][j][0] > 150 && pointLength[i][j][1] > 6) { temp = temp + "@"; balckWhite[i][j] = 1; double[] data = m2.get(i, j); data[0] = 255.0; convertArea.put(i, j, data); } else if (pointLength[i][j][0] > 7 && pointLength[i][j][1] > 200) { temp = temp + "@"; balckWhite[i][j] = 1; double[] data = m2.get(i, j); data[0] = 255.0; convertArea.put(i, j, data); } else { temp = temp + " "; balckWhite[i][j] = 0; double[] data = m2.get(i, j); data[0] = 0.0; convertArea.put(i, j, data); } } //filewrile(temp); } imshow("Convertion", convertArea); IsImage isImage = new IsImage(); HeadLineDetection isHeadline = new HeadLineDetection(); ImageBorderDetectionBFS imgBFS = new ImageBorderDetectionBFS(); ArrayList<BorderItem> borderItems = imgBFS.getBorder(balckWhite, width, hight); Mat[] subMat = new Mat[borderItems.size()]; for (int i = 0; i < borderItems.size(); i++) { subMat[i] = m2.submat(borderItems.get(i).getMinX(), borderItems.get(i).getMaxX(), borderItems.get(i).getMinY(), borderItems.get(i).getMaxY()); if (isImage.isImage(subMat[i])) { System.out.println("subMat" + i + " is an image"); //imshow("subMat" + i, subMat[i]); } else if (isHeadline.isHeadLine(subMat[i])) { System.out.println("subMat" + i + " is an Headline"); //imshow("Headline" + i, subMat[i]); } else { System.out.println("subMat" + i + " is an Column"); imshow("Column" + i, subMat[i]); } //imshow("subMat" + i, subMat[i]); bw.close(); } }