List of usage examples for org.opencv.core Mat size
public Size size()
From source file:ImagemScreen.java
public static void main(String[] args) throws InterruptedException, AWTException, IOException { JFrame f = new JFrame("Image Example"); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);/* w w w . jav a 2s . com*/ } }); ImagemScreen si = new ImagemScreen(); f.add("Center", si); // JComboBox choices = new JComboBox(si.getDescriptions()); choices.setActionCommand("SetFilter"); choices.addActionListener(si); // JComboBox formats = new JComboBox(si.getFormats()); formats.setActionCommand("Formats"); formats.addActionListener(si); // JComboBox opcao = new JComboBox(si.getComando()); opcao.setActionCommand("Escolher"); opcao.addActionListener(si); // JPanel panel = new JPanel(); panel.add(opcao); panel.add(choices); panel.add(new JLabel("Salvar como")); panel.add(formats); f.add("South", panel); f.pack(); f.setVisible(true); System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // load native library of opencv byte[] bgrPixelData = ImagemScreen.GetCurrentScreenImage(); Mat screenFrame = new Mat(600, 600, CvType.CV_8UC3); screenFrame.put(0, 0, bgrPixelData); // Create a blank output image, that we will draw onto. Mat outputFrame = new Mat(screenFrame.size(), CvType.CV_8UC3); // Save output and display the openCV Mat image onto the screen. //Gravando imagem no disco try { // ImageToScreen.DrawImageToScreen("c:\\temp\\wtf.png", outputFrame); BufferedImage teste = createBufferedImage(outputFrame); //Obtemos o contexto grfico dessa imagem Graphics2D g2d = teste.createGraphics(); File outputfile = new File("f:\\saved.png"); boolean write = ImageIO.write(teste, "png", outputfile); if (write) { System.out.println("Tudo OK!"); } g2d.dispose(); } catch (IOException e) { System.out.println("Error: " + e); } //Liberamos o contexto. }
From source file:Questao2.java
void ruidoGaussiano() { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); Mat original_Bgr = image.clone(); // cria uma imagem e inicializa com valores aleatorios Mat mGaussian_noise = new Mat(original_Bgr.size(), original_Bgr.type()); System.out.print("Valor Principal: "); int mean = in.nextInt(); System.out.print("Desvio Padro: "); int desv = in.nextInt(); // randn(matriz destino, mean value, desvio padrao) randn(mGaussian_noise, mean, desv);//from www .j a v a 2 s . c om // aplicacao do ruido: original(clone) + mGaussian_noise for (int m = 0; m < original_Bgr.rows(); m++) { for (int n = 0; n < original_Bgr.cols(); n++) { double[] val = new double[3]; for (int i = 0; i < original_Bgr.get(m, n).length; i++) { val[i] = original_Bgr.get(m, n)[i] + mGaussian_noise.get(m, n)[i]; } original_Bgr.put(m, n, val); } } // normalize(matriz entrada, matriz saida, valor minimo, valor maximo, tipo de normalizacao, tipo da imagem de saida) normalize(original_Bgr, original_Bgr, 0, 255, Core.NORM_MINMAX, CvType.CV_8UC3); // salva resultado do ruido gaussiano na imagem "gaussian.jpg" Imgcodecs.imwrite("gaussian.jpg", original_Bgr); showResult("gaussian.jpg"); }
From source file:Questao2.java
void ruidoSalPimenta() { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // obtem clone da matriz original Mat saltPepper_img = image.clone(); // cria matriz para o ruido e inicializa com valor aleatorios Mat mSaltPepper_noise = new Mat(saltPepper_img.size(), saltPepper_img.type()); // randn(matriz destino, valor principal (espectativa), desvio padrao) randn(mSaltPepper_noise, 0, 255);//from ww w .ja v a2 s.co m System.out.print("Valor Mnimo: "); int min = in.nextInt(); System.out.print("Valor Mximo: "); int max = in.nextInt(); // utilizando da matriz de numeros aleatorios, verifica valores // muito baixos e os substituem por zero na matriz resultante (copia da original) // e os valores muito altos sao substituidos por 255 for (int m = 0; m < saltPepper_img.rows(); m++) { for (int n = 0; n < saltPepper_img.cols(); n++) { double[] val = new double[3]; if (mSaltPepper_noise.get(m, n)[0] < min && mSaltPepper_noise.get(m, n)[1] < min && mSaltPepper_noise.get(m, n)[2] < min) { for (int i = 0; i < saltPepper_img.get(m, n).length; i++) { val[i] = 0; } saltPepper_img.put(m, n, val); } if (mSaltPepper_noise.get(m, n)[0] > max && mSaltPepper_noise.get(m, n)[1] > max && mSaltPepper_noise.get(m, n)[2] > max) { for (int i = 0; i < saltPepper_img.get(m, n).length; i++) { val[i] = 255; } saltPepper_img.put(m, n, val); } } } // normalize(matriz entrada, matriz saida, valor minimo, valor maximo, tipo de normalizacao, tipo da imagem de saida) normalize(saltPepper_img, saltPepper_img, 0, 255, Core.NORM_MINMAX, CvType.CV_8UC3); /** * Salva imagem resultante em saltapepper.jpg */ Imgcodecs.imwrite("saltpepper.jpg", saltPepper_img); showResult("saltpepper.jpg"); }
From source file:LicenseDetection.java
public void run() { // ------------------ set up tesseract for later use ------------------ ITesseract tessInstance = new Tesseract(); tessInstance.setDatapath("/Users/BradWilliams/Downloads/Tess4J"); tessInstance.setLanguage("eng"); // ------------------ Save image first ------------------ Mat img;//ww w . j a va2 s . c o m img = Imgcodecs.imread(getClass().getResource("/resources/car_2_shopped2.jpg").getPath()); Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/True_Image.png", img); // ------------------ Convert to grayscale ------------------ Mat imgGray = new Mat(); Imgproc.cvtColor(img, imgGray, Imgproc.COLOR_BGR2GRAY); Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/Gray.png", imgGray); // ------------------ Blur so edge detection wont pick up noise ------------------ Mat imgGaussianBlur = new Mat(); Imgproc.GaussianBlur(imgGray, imgGaussianBlur, new Size(3, 3), 0); Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/gaussian_blur.png", imgGaussianBlur); // ****************** Create image that will be cropped at end of program before OCR *************************** // ------------------ Binary theshold for OCR (used later)------------------ Mat imgThresholdOCR = new Mat(); Imgproc.adaptiveThreshold(imgGaussianBlur, imgThresholdOCR, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 7, 10); //Imgproc.threshold(imgSobel,imgThreshold,120,255,Imgproc.THRESH_TOZERO); Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgThresholdOCR.png", imgThresholdOCR); // ------------------ Erosion operation------------------ Mat kern = Imgproc.getStructuringElement(Imgproc.CV_SHAPE_CROSS, new Size(3, 3)); Mat imgErodeOCR = new Mat(); Imgproc.morphologyEx(imgThresholdOCR, imgErodeOCR, Imgproc.MORPH_DILATE, kern); //Imgproc.MORPH_DILATE is performing erosion, wtf? Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgErodeOCR.png", imgErodeOCR); //------------------ Dilation operation ------------------ Mat kernall = Imgproc.getStructuringElement(Imgproc.CV_SHAPE_RECT, new Size(3, 3)); Mat imgDilateOCR = new Mat(); Imgproc.morphologyEx(imgErodeOCR, imgDilateOCR, Imgproc.MORPH_ERODE, kernall); Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgDilateOCR.png", imgDilateOCR); // ************************************************************************************************************* // // ------------------ Close operation (dilation followed by erosion) to reduce noise ------------------ // Mat k = Imgproc.getStructuringElement(Imgproc.CV_SHAPE_RECT, new Size(3, 3)); // Mat imgCloseOCR = new Mat(); // Imgproc.morphologyEx(imgThresholdOCR,imgCloseOCR,1,k); // Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgCloseOCR.png", imgCloseOCR); // ------------------ Sobel vertical edge detection ------------------ Mat imgSobel = new Mat(); Imgproc.Sobel(imgGaussianBlur, imgSobel, -1, 1, 0); Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgSobel.png", imgSobel); // ------------------ Binary theshold ------------------ Mat imgThreshold = new Mat(); Imgproc.adaptiveThreshold(imgSobel, imgThreshold, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 99, -60); //Imgproc.threshold(imgSobel,imgThreshold,120,255,Imgproc.THRESH_TOZERO); Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgThreshold.png", imgThreshold); // // ------------------ Open operation (erosion followed by dilation) ------------------ // Mat ker = Imgproc.getStructuringElement(Imgproc.CV_SHAPE_CROSS, new Size(3, 2)); // Mat imgOpen = new Mat(); // Imgproc.morphologyEx(imgThreshold,imgOpen,0,ker); // Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgOpen.png", imgOpen); // ------------------ Close operation (dilation followed by erosion) to reduce noise ------------------ Mat kernel = Imgproc.getStructuringElement(Imgproc.CV_SHAPE_RECT, new Size(22, 8)); Mat imgClose = new Mat(); Imgproc.morphologyEx(imgThreshold, imgClose, 1, kernel); Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgClose.png", imgClose); // ------------------ Find contours ------------------ List<MatOfPoint> contours = new ArrayList<>(); Imgproc.findContours(imgClose, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE); // **************************** DEBUG CODE ************************** Mat contourImg = new Mat(imgClose.size(), imgClose.type()); for (int i = 0; i < contours.size(); i++) { Imgproc.drawContours(contourImg, contours, i, new Scalar(255, 255, 255), -1); } Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/contours.png", contourImg); // ****************************************************************** // -------------- Convert contours -------------------- //Convert to MatOfPoint2f so that minAreaRect can be called List<MatOfPoint2f> newContours = new ArrayList<>(); for (MatOfPoint mat : contours) { MatOfPoint2f newPoint = new MatOfPoint2f(mat.toArray()); newContours.add(newPoint); } //Get minAreaRects List<RotatedRect> minAreaRects = new ArrayList<>(); for (MatOfPoint2f mat : newContours) { RotatedRect rect = Imgproc.minAreaRect(mat); /* --------------- BUG WORK AROUND ------------ Possible bug: When converting from MatOfPoint2f to RotatectRect the width height were reversed and the angle was -90 degrees from what it would be if the width and height were correct. When painting rectangle in image, the correct boxes were produced, but performing calculations on rect.angle rect.width, or rect.height yielded unwanted results. The following work around is buggy but works for my purpose */ if (rect.size.width < rect.size.height) { double temp; temp = rect.size.width; rect.size.width = rect.size.height; rect.size.height = temp; rect.angle = rect.angle + 90; } //check aspect ratio and area and angle if (rect.size.width / rect.size.height > 1 && rect.size.width / rect.size.height < 5 && rect.size.width * rect.size.height > 10000 && rect.size.width * rect.size.height < 50000 && Math.abs(rect.angle) < 20) { minAreaRects.add(rect); } //minAreaRects.add(rect); } // **************************** DEBUG CODE ************************** /* The following code is used to draw the rectangles on top of the original image for debugging purposes */ //Draw Rotated Rects Point[] vertices = new Point[4]; Mat imageWithBoxes = img; // Draw color rectangles on top of binary contours // Mat imageWithBoxes = new Mat(); // Mat temp = imgDilateOCR; // Imgproc.cvtColor(temp, imageWithBoxes, Imgproc.COLOR_GRAY2RGB); for (RotatedRect rect : minAreaRects) { rect.points(vertices); for (int i = 0; i < 4; i++) { Imgproc.line(imageWithBoxes, vertices[i], vertices[(i + 1) % 4], new Scalar(0, 0, 255), 2); } } Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/imgWithBoxes.png", imageWithBoxes); // ****************************************************************** // **************************** DEBUG CODE ************************** // for(RotatedRect rect : minAreaRects) { // System.out.println(rect.toString()); // } // ****************************************************************** /* In order to rotate image without cropping it: 1. Create new square image with dimension = diagonal of initial image. 2. Draw initial image into the center of new image. Insert initial image at ROI (Region of Interest) in new image 3. Rotate new image */ //Find diagonal/hypotenuse int hypotenuse = (int) Math.sqrt((img.rows() * img.rows()) + (img.cols() * img.cols())); //New Mat with hypotenuse as height and width Mat rotateSpace = new Mat(hypotenuse, hypotenuse, 0); int ROI_x = (rotateSpace.width() - imgClose.width()) / 2; //x start of ROI int ROI_y = (rotateSpace.height() - imgClose.height()) / 2; //x start of ROI //designate region of interest Rect r = new Rect(ROI_x, ROI_y, imgClose.width(), imgClose.height()); //Insert image into region of interest imgDilateOCR.copyTo(rotateSpace.submat(r)); Mat rotatedTemp = new Mat(); //Mat to hold temporarily rotated mat Mat rectMat = new Mat();//Mat to hold rect contents (needed for looping through pixels) Point[] rectVertices = new Point[4];//Used to build rect to make ROI Rect rec = new Rect(); List<RotatedRect> edgeDensityRects = new ArrayList<>(); //populate new arraylist with rects that satisfy edge density int count = 0; //Loop through Rotated Rects and find edge density for (RotatedRect rect : minAreaRects) { count++; rect.center = new Point((float) ROI_x + rect.center.x, (float) ROI_y + rect.center.y); //rotate image to math orientation of rotated rect rotate(rotateSpace, rotatedTemp, rect.center, rect.angle); //remove rect rotation rect.angle = 0; //get vertices from rotatedRect rect.points(rectVertices); // **************************** DEBUG CODE ************************** // // for (int k = 0; k < 4; k++) { // System.out.println(rectVertices[k]); // Imgproc.line(rotatedTemp, rectVertices[k], rectVertices[(k + 1) % 4], new Scalar(0, 0, 255), 2); // } // // Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/rotated" + count + ".png", rotatedTemp); // ***************************************************************** //build rect to use as ROI rec = new Rect(rectVertices[1], rectVertices[3]); rectMat = rotatedTemp.submat(rec); Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/extracted" + count + ".png", rectMat); //find edge density // // ------------------------ edge density check NOT IMPLEMENTED -------------------- // /* // Checking for edge density was not necessary for this image so it was not implemented due to lack of time // */ // for(int i = 0; i < rectMat.rows(); ++i){ // for(int j = 0; j < rectMat.cols(); ++j){ // // //add up white pixels // } // } // // //check number of white pixels against total pixels // //only add rects to new arraylist that satisfy threshold edgeDensityRects.add(rect); } // **************************** DEBUG CODE ************************** Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/rotatedSpace.png", rotateSpace); //Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/rotatedSpaceROTATED.png", rotatedTemp); //System.out.println(imgGray.type()); // ***************************************************************** // if there is only one rectangle left, its the license plate if (edgeDensityRects.size() == 1) { String result = ""; //Hold result from OCR BufferedImage bimg; Mat cropped; cropped = rectMat.submat(new Rect(20, 50, rectMat.width() - 40, rectMat.height() - 70)); Imgcodecs.imwrite("/Users/BradWilliams/ComputerVisionOut/rectMatCropped.png", cropped); bimg = matToBufferedImage(cropped); BufferedImage image = bimg; try { result = tessInstance.doOCR(image); } catch (TesseractException e) { System.err.println(e.getMessage()); } for (int i = 0; i < 10; ++i) { } result = result.replace("\n", ""); System.out.println(result); CarProfDBImpl db = new CarProfDBImpl(); db.connect("localhost:3306/computer_vision", "root", "*******"); CarProf c = db.getCarProf(result); System.out.print(c.toString()); db.close(); } }
From source file:LicenseDetection.java
public void rotate(Mat src, Mat dst, Point point, double angle) { Mat M = Imgproc.getRotationMatrix2D(point, angle, 1.0); Imgproc.warpAffine(src, dst, M, src.size(), Imgproc.INTER_CUBIC); }
From source file:arlocros.ComputePose.java
License:Apache License
public boolean computePose(Mat rvec, Mat tvec, Mat image2) throws NyARException, FileNotFoundException { // convert image to NyAR style for processing final INyARRgbRaster imageRaster = NyARImageHelper.createFromMat(image2); // create new marker system configuration i_config = new NyARMarkerSystemConfig(i_param); markerSystemState = new NyARMarkerSystem(i_config); // Create wrapper that passes cam pictures to marker system cameraSensorWrapper = new NyARSensor(i_screen_size); ids = new int[markerPatterns.size()]; patternmap = new HashMap<>(); for (int i = 0; i < markerPatterns.size(); i++) { // create marker description from pattern file and add to marker // system ids[i] = markerSystemState.addARMarker(arCodes.get(i), 25, markerConfig.getMarkerSize()); patternmap.put(ids[i], markerPatterns.get(i)); }/*from ww w. ja va 2 s . c om*/ cameraSensorWrapper.update(imageRaster); markerSystemState.update(cameraSensorWrapper); // init 3D point list final List<Point3> points3dlist = new ArrayList<>(); final List<Point> points2dlist = new ArrayList<>(); for (final int id : ids) { // process only if this marker has been detected if (markerSystemState.isExistMarker(id) && markerSystemState.getConfidence(id) > 0.7) { // read and add 2D points final NyARIntPoint2d[] vertex2d = markerSystemState.getMarkerVertex2D(id); Point p = new Point(vertex2d[0].x, vertex2d[0].y); points2dlist.add(p); p = new Point(vertex2d[1].x, vertex2d[2].y); points2dlist.add(p); p = new Point(vertex2d[2].x, vertex2d[2].y); points2dlist.add(p); p = new Point(vertex2d[3].x, vertex2d[3].y); points2dlist.add(p); // final MatOfPoint mop = new MatOfPoint(); // mop.fromList(points2dlist); // final List<MatOfPoint> pts = new ArrayList<>(); // pts.add(mop); // read and add corresponding 3D points points3dlist.addAll(markerConfig.create3dpointlist(patternmap.get(id))); if (visualization) { // draw red rectangle around detected marker Core.rectangle(image2, new Point(vertex2d[0].x, vertex2d[0].y), new Point(vertex2d[2].x, vertex2d[2].y), new Scalar(0, 0, 255)); final String markerFile = patternmap.get(id).replaceAll(".*4x4_", "").replace(".patt", ""); Core.putText(image2, markerFile, new Point((vertex2d[2].x + vertex2d[0].x) / 2.0, vertex2d[0].y - 5), 4, 1, new Scalar(250, 0, 0)); } } } // load 2D and 3D points to Mats for solvePNP final MatOfPoint3f objectPoints = new MatOfPoint3f(); objectPoints.fromList(points3dlist); final MatOfPoint2f imagePoints = new MatOfPoint2f(); imagePoints.fromList(points2dlist); if (visualization) { // show image with markers detected Imshow.show(image2); } // do not call solvePNP with empty intput data (no markers detected) if (points2dlist.size() == 0) { objectPoints.release(); imagePoints.release(); return false; } // uncomment these lines if using RANSAC-based pose estimation (more // shaking) Mat inliers = new Mat(); Calib3d.solvePnPRansac(objectPoints, imagePoints, cameraMatrix, distCoeffs, rvec, tvec, false, 300, 5, 16, inliers, Calib3d.CV_P3P); ArMarkerPoseEstimator.getLog() .info("Points detected: " + points2dlist.size() + " inliers: " + inliers.size()); objectPoints.release(); imagePoints.release(); // avoid publish zero pose if localization failed if (inliers.rows() == 0) { inliers.release(); return false; } inliers.release(); return true; }
From source file:Clases.Analizador.java
public BufferedImage analizarCatarata(Mat img) { double[] pupila = segmentador.segmentarPupila(img); double[] clase = { 99.8125, 150.7500, 150.8125 }; double areaPupila = Math.PI * Math.pow(pupila[2], 2); int acumulador = 0; //Core.circle(img, new Point(pupila[0], pupila[1]), (int) pupila[2], new Scalar(255, 0, 0), 3); //Ventana v1 = new Ventana(convertir(max), 1, 0); //Ventana v2 = new Ventana(convertir(img), 3, 0); Size sizeA = img.size(); Mat max = img.clone();//from w ww . j ava 2 s .c o m double[] data; for (int i = 0; i < sizeA.height; i++) { for (int j = 0; j < sizeA.width; j++) { if ((Math.pow(pupila[0] - j, 2) + Math.pow(pupila[1] - i, 2) <= Math.pow(pupila[2], 2))) { data = img.get(i, j); double res = Math.sqrt(Math.pow(clase[0] - data[2], 2) + Math.pow(clase[1] - data[1], 2) + Math.pow(clase[2] - data[0], 2)); if (res < 60) { data[0] = 0; data[1] = 255; data[2] = 0; acumulador++; } max.put(i, j, data); } } } resultadoCatarata = (acumulador * 100) / areaPupila; resultadoCatarata = (double) ((int) (resultadoCatarata * 100.00) / 100); //Core.circle(imagen, new Point(pupila[0], pupila[1]), (int) pupila[2], new Scalar(255, 0, 0), 3); //Ventana v1 = new Ventana(segmentador.convertir(max), 0, 0); //Ventana v2 = new Ventana(convertir(imagen), 2, 0); return segmentador.Mat2BufferedImage(max); }
From source file:Clases.Segmentador.java
public Mat dameLaDona(Mat img1) { double[] iris = segmentarIris(img1); double[] pupila = segmentarPupila(img1); Size sizeA = img1.size(); Mat max = img1.clone();/*from w ww . j av a2s . c o m*/ double[] data; for (int i = 0; i < sizeA.height; i++) { for (int j = 0; j < sizeA.width; j++) { if ((Math.pow(iris[0] - j, 2) + Math.pow(iris[1] - i, 2) >= Math.pow(iris[2], 2)) || (Math.pow(pupila[0] - j, 2) + Math.pow(pupila[1] - i, 2) <= Math.pow(pupila[2], 2))) { data = img1.get(i, j); data[0] = 255; data[1] = 255; data[2] = 255; max.put(i, j, data); } } } return max; }
From source file:Clases.Segmentador.java
public Mat limitaIris(Mat img1) { double[] iris = segmentarIris(img1); iris[2] = iris[2] * 0.8;/*from www .jav a2 s.c om*/ Size sizeA = img1.size(); Mat max = img1.clone(); double[] data; for (int i = 0; i < sizeA.height; i++) { for (int j = 0; j < sizeA.width; j++) { if ((Math.pow(iris[0] - j, 2) + Math.pow(iris[1] - i, 2) >= Math.pow(iris[2], 2))) { data = img1.get(i, j); data[0] = 255; data[1] = 255; data[2] = 255; max.put(i, j, data); } } } return max; }
From source file:classes.ObjectFinder.java
private void computeObjectHistogram() { // Converting the current fram to HSV color space Mat hsvImage = new Mat(this.objectImage.size(), CvType.CV_8UC3); System.out.println(this.objectImage); Imgproc.cvtColor(this.objectImage, hsvImage, Imgproc.COLOR_BGR2HSV); // Getting the pixels that are in te specified ranges Mat maskImage = new Mat(this.objectImage.size(), CvType.CV_8UC1); int hmin = thresholdsVector.get(0); int hmax = thresholdsVector.get(1); int smin = thresholdsVector.get(2); int smax = thresholdsVector.get(3); int vmin = thresholdsVector.get(4); int vmax = thresholdsVector.get(5); Core.inRange(hsvImage, new Scalar(hmin, smin, vmin), new Scalar(hmax, smax, vmax), maskImage); Mat hueImage = new Mat(hsvImage.size(), CvType.CV_8UC1); MatOfInt fromto = new MatOfInt(0, 0); Core.mixChannels(Arrays.asList(hsvImage), Arrays.asList(hueImage), fromto); MatOfInt sizes = new MatOfInt(16); MatOfFloat ranges = new MatOfFloat(0, 180); MatOfInt channels = new MatOfInt(0); Mat histogram = new Mat(); boolean accumulate = false; Imgproc.calcHist(Arrays.asList(hueImage), channels, maskImage, histogram, sizes, ranges, accumulate); Highgui.imwrite("histogram.png", histogram); // The resulting histogram is normalized and placed in the class variable Core.normalize(histogram, objectHistogram, 0, 255, Core.NORM_MINMAX); }