List of usage examples for org.opencv.core Mat rows
public int rows()
From source file:servershootingstar.BallDetector.java
public static BufferedImage Mat2BufferedImage(Mat m) { // source: http://answers.opencv.org/question/10344/opencv-java-load-image-to-gui/ // The output can be assigned either to a BufferedImage or to an Image int type = BufferedImage.TYPE_BYTE_GRAY; if (m.channels() > 1) { type = BufferedImage.TYPE_3BYTE_BGR; }//from w ww . ja v a2 s. c o m int bufferSize = m.channels() * m.cols() * m.rows(); byte[] b = new byte[bufferSize]; m.get(0, 0, b); // get all the pixels BufferedImage image = new BufferedImage(m.cols(), m.rows(), type); final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); System.arraycopy(b, 0, targetPixels, 0, b.length); return image; }
From source file:servershootingstar.BallDetector.java
public static String getAngleFromRobot(int input) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); System.out.println("before"); int point;/*ww w.j av a 2 s .c o m*/ try { Mat frame = new Mat(); System.out.println("AAAAAA"); Mat originalFrame = new Mat(); System.out.println("BBBBBB"); VideoCapture videoCapture = new VideoCapture(0); System.out.println("CCCCCCCC"); videoCapture.read(originalFrame); // System.out.println("original" + originalFrame.dump()); // initSwing(originalFrame); int workaround = 20; while (workaround > 0) { System.out.println("workaround " + workaround); videoCapture.read(originalFrame); // System.out.println(originalFrame.dump() + originalFrame.dump().length()); workaround--; } // Imgcodecs.imwrite("C:\\Users\\Goran\\Desktop\\Goran.jpg", originalFrame); Mat cropped = originalFrame.submat(originalFrame.rows() / 4, originalFrame.rows() / 4 * 3, 0, originalFrame.cols()); initSwing(cropped); Imgproc.cvtColor(cropped, frame, Imgproc.COLOR_BGR2HSV); // insert lower and upper bounds for colors Scalar greenLowerB = new Scalar(20, 55, 55); Scalar greenUpperB = new Scalar(40, 255, 255); Scalar redLowerB = new Scalar(160, 100, 35); Scalar red1LowerB = new Scalar(0, 100, 35); Scalar redUpperB = new Scalar(180, 255, 255); Scalar red1UpperB = new Scalar(20, 255, 255); Scalar blueLowerB = new Scalar(100, 100, 35); Scalar blueUpperB = new Scalar(120, 255, 155); Mat mask = new Mat(); if (input == 1) { Mat otherMask = new Mat(); Core.inRange(frame, redLowerB, redUpperB, mask); Core.inRange(frame, red1LowerB, red1UpperB, otherMask); Core.bitwise_or(mask, otherMask, mask); } else if (input == 2) { Core.inRange(frame, greenLowerB, greenUpperB, mask); } else { Core.inRange(frame, blueLowerB, blueUpperB, mask); } Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5))); Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5))); Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5))); Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5))); int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE, minY = Integer.MAX_VALUE, maxY = Integer.MIN_VALUE; for (int i = 0; i < mask.rows(); ++i) { for (int j = 0; j < mask.cols(); ++j) { double value = mask.get(i, j)[0]; //System.out.println(value); if (value > 1) { minX = Math.min(minX, i); maxX = Math.max(maxX, i); minY = Math.min(minY, j); maxY = Math.max(maxY, j); } } } Imgproc.circle(mask, new Point((maxY + minY) / 2, (minX + maxX) / 2), 3, new Scalar(0, 0, 0)); initSwing(mask); point = (minY + maxY) / 2; point = point - 320; cos = point / 320.0; System.out.println("OK"); } catch (Exception ex) { point = (new Random()).nextInt(640); cos = -1; System.out.println("error imase, davam random brojka: " + point); ex.printStackTrace(); } // System.out.println(); // System.out.println("tockata u granica od [-320, 320]"); // System.out.println(point); // System.out.println("cosinus vrednost"); // System.out.println(cos); // System.out.println(); System.out.println("cos = " + cos); if (cos == -1) { return "-1"; } int res = (int) (2 * Math.toDegrees(Math.acos(cos)) / 3); System.out.println("Res: " + res); return String.valueOf(res); }
From source file:servlets.FillAreaByScribble.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//w ww . jav a2 s . c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String imageForTextRecognition = request.getParameter("imageForTextRecognition") + ".png"; String isSingleRegion = request.getParameter("isSingleRegion"); boolean makeSingleRegion = isSingleRegion.toLowerCase().equals("true"); Mat original = ImageUtils.loadImage(imageForTextRecognition, request); Mat image = original.clone(); Mat mask = Mat.zeros(image.rows() + 2, image.cols() + 2, CvType.CV_8UC1); String samplingPoints = request.getParameter("samplingPoints"); Gson gson = new Gson(); Point[] tmpPoints = gson.fromJson(samplingPoints, Point[].class); ArrayList<Point> userPoints = new ArrayList<Point>(Arrays.asList(tmpPoints)); Mat userPointsImage = image.clone(); ArrayList<Mat> maskRegions = new ArrayList<>(); Random random = new Random(); int b = random.nextInt(256); int g = random.nextInt(256); int r = random.nextInt(256); Scalar newVal = new Scalar(b, g, r); FloodFillFacade floodFillFacade = new FloodFillFacade(); int k = 0; for (int i = 0; i < userPoints.size(); i++) { Point point = userPoints.get(i); image = floodFillFacade.fill(image, mask, (int) point.x, (int) point.y, newVal); Mat seedImage = original.clone(); Core.circle(seedImage, point, 9, new Scalar(0, 0, 255), -1); Core.putText(userPointsImage, "" + k, new Point(point.x + 5, point.y + 5), 3, 0.5, new Scalar(0, 0, 0)); // ImageUtils.saveImage(seedImage, "mask_" + k + "_seed" + imageForTextRecognition + ".png", request); if (!makeSingleRegion) { Mat element = new Mat(3, 3, CvType.CV_8U, new Scalar(1)); Imgproc.morphologyEx(mask, mask, Imgproc.MORPH_CLOSE, element, new Point(-1, -1), 3); Imgproc.resize(mask, mask, original.size()); } // ImageUtils.saveImage(mask, "mask_" + k + "" + imageForTextRecognition + ".png", request); Mat dilatedMask = new Mat(); int elementSide = 21; Mat element = new Mat(elementSide, elementSide, CvType.CV_8U, new Scalar(1)); Imgproc.morphologyEx(mask, dilatedMask, Imgproc.MORPH_DILATE, element, new Point(-1, -1), 1); Imgproc.resize(dilatedMask, dilatedMask, original.size()); // ImageUtils.saveImage(dilatedMask, "mask_" + k + "_dilated" + imageForTextRecognition + ".png", request); maskRegions.add(mask); if (!makeSingleRegion) { int totalRemovedPoints = filterPoints(userPoints, dilatedMask); if (totalRemovedPoints > 0) { i = -1; // so that the algorithm starts again at the first element of the userPoints array } } else { filterPoints(userPoints, mask); } // System.out.println("Total points after filtering:"); // System.out.println(userPoints.size()); if (!makeSingleRegion) { mask = Mat.zeros(original.rows() + 2, original.cols() + 2, CvType.CV_8UC1); } k++; } ArrayList<FindingResponse> findingResponses = new ArrayList<>(); if (makeSingleRegion) { Mat element = new Mat(3, 3, CvType.CV_8U, new Scalar(1)); Imgproc.morphologyEx(mask, mask, Imgproc.MORPH_CLOSE, element, new Point(-1, -1), 3); Imgproc.resize(mask, mask, image.size()); List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Imgproc.findContours(mask.clone(), contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE); MatOfPoint biggestContour = contours.get(0); // getting the biggest contour double contourArea = Imgproc.contourArea(biggestContour); if (contours.size() > 1) { biggestContour = Collections.max(contours, new ContourComparator()); // getting the biggest contour in case there are more than one } Point[] biggestContourPoints = biggestContour.toArray(); String path = "M " + (int) biggestContourPoints[0].x + " " + (int) biggestContourPoints[0].y + " "; for (int i = 1; i < biggestContourPoints.length; ++i) { Point v = biggestContourPoints[i]; path += "L " + (int) v.x + " " + (int) v.y + " "; } path += "Z"; // System.out.println("path:"); // System.out.println(path); Rect computedSearchWindow = Imgproc.boundingRect(biggestContour); Point massCenter = computedSearchWindow.tl(); Scalar meanColor = Core.mean(original, mask); // ImageUtils.saveImage(mask, "single_mask_" + imageForTextRecognition + ".png", request); FindingResponse findingResponse = new FindingResponse(path, meanColor, massCenter, -1, contourArea); findingResponses.add(findingResponse); } else { float imageArea = image.cols() * image.rows(); for (int j = 0; j < maskRegions.size(); j++) { Mat region = maskRegions.get(j); List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Imgproc.findContours(region.clone(), contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE); MatOfPoint biggestContour = contours.get(0); // getting the biggest contour if (contours.size() > 1) { biggestContour = Collections.max(contours, new ContourComparator()); // getting the biggest contour in case there are more than one } double contourArea = Imgproc.contourArea(biggestContour); if (contourArea / imageArea < 0.8) { // only areas less than 80% of that of the image are accepted Point[] biggestContourPoints = biggestContour.toArray(); String path = "M " + (int) biggestContourPoints[0].x + " " + (int) biggestContourPoints[0].y + " "; for (int i = 1; i < biggestContourPoints.length; ++i) { Point v = biggestContourPoints[i]; path += "L " + (int) v.x + " " + (int) v.y + " "; } path += "Z"; Rect computedSearchWindow = Imgproc.boundingRect(biggestContour); Point massCenter = computedSearchWindow.tl(); // System.out.println("Contour area: " + contourArea); Mat contoursImage = userPointsImage.clone(); Imgproc.drawContours(contoursImage, contours, 0, newVal, 1); Scalar meanColor = Core.mean(original, region); FindingResponse findingResponse = new FindingResponse(path, meanColor, massCenter, -1, contourArea); findingResponses.add(findingResponse); // ImageUtils.saveImage(contoursImage, "mask_" + j + "_contourned" + imageForTextRecognition + ".png", request); } } } String jsonResponse = gson.toJson(findingResponses, ArrayList.class); out.println(jsonResponse); } }
From source file:servlets.processScribble.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// ww w . ja va 2s .co m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String imageForTextRecognition = request.getParameter("imageForTextRecognition") + ".png"; Mat original = ImageUtils.loadImage(imageForTextRecognition, request); Mat image = original.clone(); Mat mask = Mat.zeros(image.rows() + 2, image.cols() + 2, CvType.CV_8UC1); String samplingPoints = request.getParameter("samplingPoints"); Gson gson = new Gson(); Point[] userPoints = gson.fromJson(samplingPoints, Point[].class); MatOfPoint points = new MatOfPoint(new Mat(userPoints.length, 1, CvType.CV_32SC2)); int cont = 0; for (Point point : userPoints) { int y = (int) point.y; int x = (int) point.x; int[] data = { x, y }; points.put(cont++, 0, data); } MatOfInt hull = new MatOfInt(); Imgproc.convexHull(points, hull); MatOfPoint mopOut = new MatOfPoint(); mopOut.create((int) hull.size().height, 1, CvType.CV_32SC2); int totalPoints = (int) hull.size().height; Point[] convexHullPoints = new Point[totalPoints]; ArrayList<Point> seeds = new ArrayList<>(); for (int i = 0; i < totalPoints; i++) { int index = (int) hull.get(i, 0)[0]; double[] point = new double[] { points.get(index, 0)[0], points.get(index, 0)[1] }; mopOut.put(i, 0, point); convexHullPoints[i] = new Point(point[0], point[1]); seeds.add(new Point(point[0], point[1])); } MatOfPoint mop = new MatOfPoint(); mop.fromArray(convexHullPoints); ArrayList<MatOfPoint> arrayList = new ArrayList<MatOfPoint>(); arrayList.add(mop); Random random = new Random(); int b = random.nextInt(256); int g = random.nextInt(256); int r = random.nextInt(256); Scalar newVal = new Scalar(b, g, r); FloodFillFacade floodFillFacade = new FloodFillFacade(); for (int i = 0; i < seeds.size(); i++) { Point seed = seeds.get(i); image = floodFillFacade.fill(image, mask, (int) seed.x, (int) seed.y, newVal); } Imgproc.drawContours(image, arrayList, 0, newVal, -1); Imgproc.resize(mask, mask, image.size()); Scalar meanColor = Core.mean(original, mask); // Highgui.imwrite("C:\\Users\\Gonzalo\\Documents\\NetBeansProjects\\iVoLVER\\uploads\\the_convexHull.png", image); ImageUtils.saveImage(image, imageForTextRecognition + "_the_convexHull.png", request); newVal = new Scalar(255, 255, 0); floodFillFacade.setMasked(false); System.out.println("Last one:"); floodFillFacade.fill(image, mask, 211, 194, newVal); Core.circle(image, new Point(211, 194), 5, new Scalar(0, 0, 0), -1); ImageUtils.saveImage(image, imageForTextRecognition + "_final.png", request); // Highgui.imwrite("C:\\Users\\Gonzalo\\Documents\\NetBeansProjects\\iVoLVER\\uploads\\final.png", image); Mat element = new Mat(3, 3, CvType.CV_8U, new Scalar(1)); Imgproc.morphologyEx(mask, mask, Imgproc.MORPH_CLOSE, element, new Point(-1, -1), 3); Imgproc.resize(mask, mask, image.size()); // ImageUtils.saveImage(mask, "final_mask_dilated.png", request); // Highgui.imwrite("C:\\Users\\Gonzalo\\Documents\\NetBeansProjects\\iVoLVER\\uploads\\final_mask_dilated.png", mask); List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Imgproc.findContours(mask.clone(), contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE); double contourArea = 0; String path = ""; MatOfPoint biggestContour = contours.get(0); // getting the biggest contour contourArea = Imgproc.contourArea(biggestContour); if (contours.size() > 1) { biggestContour = Collections.max(contours, new ContourComparator()); // getting the biggest contour in case there are more than one } Point[] biggestContourPoints = biggestContour.toArray(); path = "M " + (int) biggestContourPoints[0].x + " " + (int) biggestContourPoints[0].y + " "; for (int i = 1; i < biggestContourPoints.length; ++i) { Point v = biggestContourPoints[i]; path += "L " + (int) v.x + " " + (int) v.y + " "; } path += "Z"; System.out.println("path:"); System.out.println(path); Rect computedSearchWindow = Imgproc.boundingRect(biggestContour); Point massCenter = computedSearchWindow.tl(); FindingResponse findingResponse = new FindingResponse(path, meanColor, massCenter, -1, contourArea); String jsonResponse = gson.toJson(findingResponse, FindingResponse.class); out.println(jsonResponse); // String jsonResponse = gson.toJson(path); // out.println(jsonResponse); } }
From source file:servlets.SampleColorsFromImageObject.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . ja v a 2 s . co m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String imageForTextRecognition = request.getParameter("imageForTextRecognition") + ".png"; Mat image = ImageUtils.loadImage(imageForTextRecognition, request); String samplingPoints = request.getParameter("samplingPoints"); ArrayList<int[]> results = new ArrayList<>(); Gson gson = new Gson(); Point[] samplingPositions = gson.fromJson(samplingPoints, Point[].class); for (Point point : samplingPositions) { int row = (int) point.y; int col = (int) point.x; int totalCols = image.cols(); int totalRows = image.rows(); int b = -1; int g = -1; int r = -1; if (row >= 0 && col >= 0 && col < totalCols && row < totalRows) { double[] color = image.get(row, col); b = (int) color[0]; g = (int) color[1]; r = (int) color[2]; } int[] intColor = { r, g, b }; results.add(intColor); System.out.println("Color at: (" + row + ", " + col + "): " + r + " " + g + " " + b); } String jsonResponse = gson.toJson(results); out.println(jsonResponse); } }
From source file:spring2017ip.ConvolutionDemo.java
public Mat convolute(Mat inputImage, double kernel[][], double anchorX, double anchorY) { Mat outputImage = new Mat(inputImage.rows(), inputImage.cols(), inputImage.type()); // have to fix this code so that it works for any sized kernel for (int i = 1; i < inputImage.rows() - 1; i++) for (int j = 1; j < inputImage.cols() - 1; j++) { double sum = 0; for (int r = 0; r < kernel.length; r++) for (int c = 0; c < kernel[r].length; c++) { double pixel[] = inputImage.get(i - kernel.length / 2 + r, j - kernel[0].length / 2 + c); double product = kernel[r][c] * pixel[0]; sum = sum + product; }/*www . jav a2 s . co m*/ outputImage.put(i, j, sum); } return outputImage; }
From source file:spring2017ip.ConvolutionDemo.java
public Mat combineGxGy(Mat gx, Mat gy) { Mat outputImage = new Mat(gx.rows(), gx.cols(), gx.type()); for (int r = 0; r < gx.height(); r++) for (int c = 0; c < gx.width(); c++) { double x[] = gx.get(r, c); double y[] = gy.get(r, c); double m = Math.sqrt(x[0] * x[0] + y[0] * y[0]); outputImage.put(r, c, m);/* w ww.ja v a 2 s .c om*/ } return outputImage; }
From source file:src.model.filters.CannyFilter.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("**______________CANNY_______________**"); try {//from w w w . j a v a 2 s . c om String imgInput = request.getParameter("name").toString(); String savePath = savePath(request); //____________________________________ Mat source = Imgcodecs.imread(savePath); Mat destination = new Mat(source.rows(), source.cols(), source.type()); Mat det = new Mat(source.rows(), source.cols(), source.type()); Imgproc.cvtColor(source, destination, Imgproc.COLOR_BGR2GRAY); Imgproc.blur(destination, det, new Size(3, 3)); Imgproc.Canny(det, det, 5, 15, 3, false); Mat dest = new Mat(); Core.add(dest, Scalar.all(0), dest); source.copyTo(dest, det); String output = savePath.substring(0, savePath.lastIndexOf(".")) + "_CA_temp.jpg"; imgInput = request.getParameter("name").toString(); String imgOutput = imgInput.substring(0, imgInput.lastIndexOf(".")) + "_CA_temp.jpg"; Imgcodecs.imwrite(output, dest); //____________________________________ System.out.println("output: " + output); System.out.println("imgOutput: " + imgOutput); publishImg(response, imgOutput); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } }
From source file:src.model.filters.DilationFilter.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("**______________DILATION_______________**"); try {/* w ww . j av a 2 s .c om*/ String imgInput = request.getParameter("name").toString(); System.out.println("imgIn put " + imgInput); String savePath = savePath(request); //____________________________________ Mat source = Imgcodecs.imread(savePath, Imgcodecs.CV_LOAD_IMAGE_COLOR); Mat destination = new Mat(source.rows(), source.cols(), source.type()); destination = source; int dilation_size = 5; Mat element = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(2 * dilation_size + 1, 2 * dilation_size + 1)); Imgproc.dilate(source, destination, element); // src.model.ApplyFilter.deleteTemps(output); String output = savePath.substring(0, savePath.lastIndexOf(".")) + "_DIL_temp.jpg"; String imgOutput = imgInput.substring(0, imgInput.lastIndexOf(".")) + "_DIL_temp.jpg"; Imgcodecs.imwrite(output, destination); //____________________________________ System.out.println("output: " + output); publishImg(response, imgOutput); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } }
From source file:src.model.filters.DotsFilter.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("**______________DOTS_______________**"); try {/*w ww . j ava2 s .c o m*/ String imgInput = request.getParameter("name").toString(); String savePath = savePath(request); //____________________________________ int elementSize = 2; int bsize = 10; Mat source = Imgcodecs.imread(savePath); Mat dst = zeros(source.size(), CV_8UC3); Mat cir = zeros(source.size(), CV_8UC1); Mat destination = new Mat(source.rows(), source.cols(), source.type()); Mat element = Imgproc.getStructuringElement(Imgproc.CV_SHAPE_RECT, new Size(elementSize * 3 + 1, elementSize * 3 + 1), new Point(elementSize, elementSize)); for (int i = 0; i < source.rows(); i += bsize) { for (int j = 0; j < source.cols(); j += bsize) { circle(cir, new Point(j + bsize / (double) 2, i + bsize / (double) 2), bsize / 2 - 1, new Scalar(255, 255, 255), -1, -1, Core.LINE_AA); } } Imgproc.morphologyEx(source, dst, Imgproc.MORPH_CLOSE, element); Mat cir_32f = new Mat(source.rows(), source.cols(), CV_32F); cir.convertTo(cir_32f, CV_32F); normalize(cir_32f, cir_32f, 0, 1, NORM_MINMAX); Mat dst_32f = new Mat(source.rows(), source.cols(), CV_32F); dst.convertTo(dst_32f, CV_32F); Vector<Mat> channels = new Vector(); split(dst_32f, channels); System.out.println(channels.size()); for (int i = 0; i < channels.size(); ++i) { channels.set(i, channels.get(i).mul(cir_32f)); } merge(channels, dst_32f); dst_32f.convertTo(dst, CV_8U); // Core.gemm(source, source, bsize, source, bsize, dst); // Core.gemm(cir, destination, 1, new Mat(), 0,dst , 0); // Imgcodecs.imwrite("images\\outddput.jpg", dst); String output = savePath.substring(0, savePath.lastIndexOf(".")) + "_DOTS_temp.jpg"; imgInput = request.getParameter("name").toString(); String imgOutput = imgInput.substring(0, imgInput.lastIndexOf(".")) + "_DOTS_temp.jpg"; Imgcodecs.imwrite(output, dst); //____________________________________ System.out.println("output: " + output); System.out.println("imgOutput: " + imgOutput); publishImg(response, imgOutput); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } }