List of usage examples for org.opencv.core Mat Mat
public Mat()
From source file:ThirdTry.java
public static void main(String[] args) { // Load an image file and display it in a window. Mat m1 = Highgui.imread("H:\\error35.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);//from w ww .jav a 2 s. c om imshow("Edge Detected", m2); detectLetter(m1, m2); }
From source file:ThirdTry.java
public static void detectLetter(Mat img, Mat m2) { ArrayList<Rect> boundRect = new ArrayList<>(); Mat img_gray, img_sobel, img_threshold, element; img_gray = new Mat(); img_sobel = new Mat(); img_threshold = new Mat(); element = new Mat(); Imgproc.cvtColor(img, img_gray, Imgproc.COLOR_BGRA2GRAY); //imshow("Rec img_gray", img_gray); Imgproc.Sobel(img_gray, img_sobel, CvType.CV_8UC1, 1, 0, 3, 1, 0, Imgproc.BORDER_DEFAULT); //imshow("Rec img_sobel", img_sobel); Imgproc.threshold(m2, img_threshold, 0, 255, CV_THRESH_OTSU + CV_THRESH_BINARY); //imshow("Rec img_threshold", img_threshold); element = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(3, 2)); Imgproc.morphologyEx(m2, img_threshold, CV_MOP_CLOSE, element); imshow("Rec img_threshold second", img_threshold); element = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(12, 12)); Imgproc.morphologyEx(img_threshold, img_threshold, CV_MOP_CLOSE, element); //imshow("Rec img_threshold second", img_threshold); List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); //Imgproc.findContours(img_threshold, contours, new Mat(), Imgproc.RETR_LIST,Imgproc.CHAIN_APPROX_SIMPLE); Imgproc.findContours(img_threshold, contours, new Mat(), 0, 1); for (int i = 0; i < contours.size(); i++) { System.out.println(Imgproc.contourArea(contours.get(i))); // if (Imgproc.contourArea(contours.get(i)) > 100) { // //Imgproc.approxPolyDP( contours.get(i), contours_poly[i], 3, true ); // Rect rect = Imgproc.boundingRect(contours.get(i)); // System.out.println(rect.height); // if (rect.width > rect.height) { // //System.out.println(rect.x +","+rect.y+","+rect.height+","+rect.width); // Core.rectangle(img, new Point(rect.x,rect.y), new Point(rect.x+rect.width,rect.y+rect.height),new Scalar(0,0,255)); // } // // // } if (Imgproc.contourArea(contours.get(i)) > 100) { MatOfPoint2f mMOP2f1 = new MatOfPoint2f(); MatOfPoint2f mMOP2f2 = new MatOfPoint2f(); contours.get(i).convertTo(mMOP2f1, CvType.CV_32FC2); Imgproc.approxPolyDP(mMOP2f1, mMOP2f2, 3, true); mMOP2f2.convertTo(contours.get(i), CvType.CV_32S); Rect rect = Imgproc.boundingRect(contours.get(i)); if (rect.width > rect.height) { Core.rectangle(img, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 0, 255)); }/*ww w . j ava2 s.co m*/ } } //imshow("Rec Detected", img); }
From source file:OctoEye.java
License:Open Source License
private void detectPupil() { // min and max pupil radius int r_min = 2; int r_max = 45; // min and max pupil diameter int d_min = 2 * r_min; int d_max = 2 * r_max; // min and max pupil area double area;/*from w w w . ja v a 2s . co m*/ double a_min = Math.PI * r_min * r_min; double a_max = Math.PI * r_max * r_max; // histogram stuff List<Mat> images; MatOfInt channels; Mat mask; Mat hist; MatOfInt mHistSize; MatOfFloat mRanges; // contour and circle stuff Rect rect = null; Rect rectMin; Rect rectMax; List<MatOfPoint> contours; MatOfPoint3 circles; // pupil center Point p; // ellipse test points Point v; Point r; Point s; // rect points Point tl; Point br; // pupil edge detection Vector<Point> pointsTest; Vector<Point> pointsEllipse; Vector<Point> pointsRemoved; // temporary variables double distance; double rad; double length; int x; int y; int tmp; byte buff[]; // ------------------------------------------------------------------------------------------------------------- // step 1 // blur the image to reduce noise Imgproc.medianBlur(src, tmp1, 25); // ------------------------------------------------------------------------------------------------------------- // step 2 // locate the pupil with feature detection and compute a histogram for each, // the best feature will be used as rough pupil location (rectMin) int score = 0; int winner = 0; // feature detection MatOfKeyPoint matOfKeyPoints = new MatOfKeyPoint(); FeatureDetector blobDetector = FeatureDetector.create(FeatureDetector.MSER); // Maximal Stable Extremal Regions blobDetector.detect(tmp1, matOfKeyPoints); List<KeyPoint> keyPoints = matOfKeyPoints.toList(); // histogram calculation for (int i = 0; i < keyPoints.size(); i++) { x = (int) keyPoints.get(i).pt.x; y = (int) keyPoints.get(i).pt.y; tl = new Point(x - 5 >= 0 ? x - 5 : 0, y - 5 >= 0 ? y - 5 : 0); br = new Point(x + 5 < WIDTH ? x + 5 : WIDTH - 1, y + 5 < HEIGHT ? y + 5 : HEIGHT - 1); images = new ArrayList<Mat>(); images.add(tmp1.submat(new Rect(tl, br))); channels = new MatOfInt(0); mask = new Mat(); hist = new Mat(); mHistSize = new MatOfInt(256); mRanges = new MatOfFloat(0f, 256f); Imgproc.calcHist(images, channels, mask, hist, mHistSize, mRanges); tmp = 0; for (int j = 0; j < 256 / 3; j++) { tmp += (256 / 3 - j) * (int) hist.get(j, 0)[0]; } if (tmp >= score) { score = tmp; winner = i; rect = new Rect(tl, br); } if (debug) { // show features (orange) Core.circle(dbg, new Point(x, y), 3, ORANGE); } } if (rect == null) { return; } rectMin = rect.clone(); if (debug) { // show rectMin (red) Core.rectangle(dbg, rectMin.tl(), rect.br(), RED, 1); } // ------------------------------------------------------------------------------------------------------------- // step 3 // compute a rectMax (blue) which is larger than the pupil int margin = 32; rect.x = rect.x - margin; rect.y = rect.y - margin; rect.width = rect.width + 2 * margin; rect.height = rect.height + 2 * margin; rectMax = rect.clone(); if (debug) { // show features (orange) Core.rectangle(dbg, rectMax.tl(), rectMax.br(), BLUE); } // ------------------------------------------------------------------------------------------------------------- // step 4 // blur the image again Imgproc.medianBlur(src, tmp1, 7); Imgproc.medianBlur(tmp1, tmp1, 3); Imgproc.medianBlur(tmp1, tmp1, 3); Imgproc.medianBlur(tmp1, tmp1, 3); // ------------------------------------------------------------------------------------------------------------- // step 5 // detect edges Imgproc.Canny(tmp1, tmp2, 40, 50); // ------------------------------------------------------------------------------------------------------------- // step 6 // from pupil center to maxRect borders, find all edge points, compute a first ellipse p = new Point(rectMin.x + rectMin.width / 2, rectMin.y + rectMin.height / 2); pointsTest = new Vector<Point>(); pointsEllipse = new Vector<Point>(); pointsRemoved = new Vector<Point>(); buff = new byte[tmp2.rows() * tmp2.cols()]; tmp2.get(0, 0, buff); length = Math.min(p.x - rectMax.x - 3, p.y - rectMax.y - 3); length = Math.sqrt(2 * Math.pow(length, 2)); Point z = new Point(p.x, p.y - length); for (int i = 0; i < 360; i += 15) { rad = Math.toRadians(i); x = (int) (p.x + Math.cos(rad) * (z.x - p.x) - Math.sin(rad) * (z.y - p.y)); y = (int) (p.y + Math.sin(rad) * (z.x - p.x) - Math.cos(rad) * (z.y - p.y)); pointsTest.add(new Point(x, y)); } if (debug) { for (int i = 0; i < pointsTest.size(); i++) { Core.line(dbg, p, pointsTest.get(i), GRAY, 1); Core.rectangle(dbg, rectMin.tl(), rectMin.br(), GREEN, 1); Core.rectangle(dbg, rectMax.tl(), rectMax.br(), BLUE, 1); } Core.rectangle(dbg, rectMin.tl(), rectMin.br(), BLACK, -1); Core.rectangle(dbg, rectMin.tl(), rectMin.br(), RED, 1); Core.rectangle(dbg, rectMax.tl(), rectMax.br(), BLUE); } // p: Ursprung ("Mittelpunkt" der Ellipse) // v: Zielpunkt (Testpunkt) // r: Richtungsvektor PV for (int i = 0; i < pointsTest.size(); i++) { v = new Point(pointsTest.get(i).x, pointsTest.get(i).y); r = new Point(v.x - p.x, v.y - p.y); length = Math.sqrt(Math.pow(p.x - v.x, 2) + Math.pow(p.y - v.y, 2)); boolean found = false; for (int j = 0; j < Math.round(length); j++) { s = new Point(Math.rint(p.x + (double) j / length * r.x), Math.rint(p.y + (double) j / length * r.y)); s.x = Math.max(1, Math.min(s.x, WIDTH - 2)); s.y = Math.max(1, Math.min(s.y, HEIGHT - 2)); tl = new Point(s.x - 1, s.y - 1); br = new Point(s.x + 1, s.y + 1); buff = new byte[3 * 3]; rect = new Rect(tl, br); try { (tmp2.submat(rect)).get(0, 0, buff); for (int k = 0; k < 3 * 3; k++) { if (Math.abs(buff[k]) == 1) { pointsEllipse.add(s); found = true; break; } } } catch (Exception e) { break; } if (found) { break; } } } double e_min = Double.POSITIVE_INFINITY; double e_max = 0; double e_med = 0; for (int i = 0; i < pointsEllipse.size(); i++) { v = pointsEllipse.get(i); length = Math.sqrt(Math.pow(p.x - v.x, 2) + Math.pow(p.y - v.y, 2)); e_min = (length < e_min) ? length : e_min; e_max = (length > e_max) ? length : e_max; e_med = e_med + length; } e_med = e_med / pointsEllipse.size(); if (pointsEllipse.size() >= 5) { Point[] points1 = new Point[pointsEllipse.size()]; for (int i = 0; i < pointsEllipse.size(); i++) { points1[i] = pointsEllipse.get(i); } MatOfPoint2f points2 = new MatOfPoint2f(); points2.fromArray(points1); pupil = Imgproc.fitEllipse(points2); } if (pupil.center.x == 0 && pupil.center.y == 0) { // something went wrong, return null reset(); return; } if (debug) { Core.ellipse(dbg, pupil, PURPLE, 2); } // ------------------------------------------------------------------------------------------------------------- // step 7 // remove some outlier points and compute the ellipse again try { for (int i = 1; i <= 4; i++) { distance = 0; int remove = 0; for (int j = pointsEllipse.size() - 1; j >= 0; j--) { v = pointsEllipse.get(j); length = Math.sqrt(Math.pow(v.x - pupil.center.x, 2) + Math.pow(v.y - pupil.center.y, 2)); if (length > distance) { distance = length; remove = j; } } v = pointsEllipse.get(remove); pointsEllipse.removeElementAt(remove); pointsRemoved.add(v); } } catch (Exception e) { // something went wrong, return null reset(); return; } if (pointsEllipse.size() >= 5) { Point[] points1 = new Point[pointsEllipse.size()]; for (int i = 0; i < pointsEllipse.size(); i++) { points1[i] = pointsEllipse.get(i); } MatOfPoint2f points2 = new MatOfPoint2f(); points2.fromArray(points1); pupil = Imgproc.fitEllipse(points2); Point[] vertices = new Point[4]; pupil.points(vertices); double d1 = Math .sqrt(Math.pow(vertices[1].x - vertices[0].x, 2) + Math.pow(vertices[1].y - vertices[0].y, 2)); double d2 = Math .sqrt(Math.pow(vertices[2].x - vertices[1].x, 2) + Math.pow(vertices[2].y - vertices[1].y, 2)); if (d1 >= d2) { pupilMajorAxis = (int) (d1 / 2); pupilMinorAxis = (int) (d2 / 2); axisA = new Point(vertices[1].x + (vertices[2].x - vertices[1].x) / 2, vertices[1].y + (vertices[2].y - vertices[1].y) / 2); axisB = new Point(vertices[0].x + (vertices[1].x - vertices[0].x) / 2, vertices[0].y + (vertices[1].y - vertices[0].y) / 2); } else { pupilMajorAxis = (int) (d2 / 2); pupilMinorAxis = (int) (d1 / 2); axisB = new Point(vertices[1].x + (vertices[2].x - vertices[1].x) / 2, vertices[1].y + (vertices[2].y - vertices[1].y) / 2); axisA = new Point(vertices[0].x + (vertices[1].x - vertices[0].x) / 2, vertices[0].y + (vertices[1].y - vertices[0].y) / 2); } } double ratio = (double) pupilMinorAxis / (double) pupilMajorAxis; if (ratio < 0.75 || 2 * pupilMinorAxis <= d_min || 2 * pupilMajorAxis >= d_max) { // something went wrong, return null reset(); return; } // pupil found if (debug) { Core.ellipse(dbg, pupil, GREEN, 2); Core.line(dbg, pupil.center, axisA, RED, 2); Core.line(dbg, pupil.center, axisB, BLUE, 2); Core.circle(dbg, pupil.center, 1, GREEN, 0); x = 5; y = 5; Core.rectangle(dbg, new Point(x, y), new Point(x + 80 + 4, y + 10), BLACK, -1); Core.rectangle(dbg, new Point(x + 2, y + 2), new Point(x + 2 + pupilMajorAxis, y + 4), RED, -1); Core.rectangle(dbg, new Point(x + 2, y + 6), new Point(x + 2 + pupilMinorAxis, y + 8), BLUE, -1); for (int i = pointsEllipse.size() - 1; i >= 0; i--) { Core.circle(dbg, pointsEllipse.get(i), 2, ORANGE, -1); } for (int i = pointsRemoved.size() - 1; i >= 0; i--) { Core.circle(dbg, pointsRemoved.get(i), 2, PURPLE, -1); } } Core.ellipse(dst, pupil, GREEN, 2); Core.circle(dst, pupil.center, 1, GREEN, 0); }
From source file:Face_Reco.java
public static void main(String args[]) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); VideoCapture camera = new VideoCapture(0); if (!camera.isOpened()) { System.out.println("Error"); } else {//from w w w .j av a 2 s .c o m Mat frame = new Mat(); while (true) { if (camera.read(frame)) { System.out.println("Frame Obtained"); System.out.println("Captured Frame Width" + frame.width() + "Height" + frame.height()); Imgcodecs.imwrite("Camera.jpg", frame); Imgcodecs.imread("camera.jpg"); Imgcodecs.imread("camera.jpg", Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE); System.out.println("Done!"); break; } } } camera.release(); }
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;/*from w ww . ja v a 2 s . co 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:Retrive.java
public void reterives(String path, int n) { Retrive r = new Retrive(); Test1 ts = new Test1(); System.loadLibrary(Core.NATIVE_LIBRARY_NAME); Frame f = new Frame(); FileDialog fd = new FileDialog(f, "input directory", FileDialog.LOAD); fd.setVisible(true);// w ww. ja v a 2s.c o m File directory = new File(fd.getDirectory()); File[] list = directory.listFiles(); int len = directory.listFiles().length; Mat[] img_corpse = new Mat[len]; Mat[] histo = new Mat[len]; for (int i = 0; i < len; i++) { img_corpse[i] = Highgui.imread(list[i].toString()); //Imgproc.cvtColor(img_corpse[i],img_corpse[i], Imgproc.COLOR_RGB2GRAY); System.out.println(list[i]); //System.out.println(img_corpse[i].dump()); histo[i] = r.histo(img_corpse[i]); } distanceofn nd = new distanceofn(); Mat query = Highgui.imread(path); Imgproc.cvtColor(query, query, Imgproc.COLOR_RGB2GRAY); Double[] distance = new Double[len]; Mat histquery = new Mat(); histquery = r.query_histo(query); for (int i = 0; i < len; i++) { r.RGBtoGRAY(query, img_corpse[i]); r.Preprocess(query, img_corpse[i]); System.out.println("size of query" + query.width() + query.height()); System.out.println("size of datacorpus" + img_corpse[i].width() + img_corpse[i].height()); //Imshow im = new Imshow("title"); //im.showImage(img_corpse[i]); distance[i] = r.Find_dist(histquery, histo[i]); //distance[i]=nd.ndistance(histquery, histo[i], 2); } for (int i = 0; i < len; i++) { System.out.println("distance of " + i + " " + distance[i]); } r.map(list, distance, len); }
From source file:Retrive.java
public Mat query_histo(Mat query_img) { Vector<Mat> bgr_planes = new Vector<>(); Core.split(query_img, bgr_planes);//from w ww . ja v a 2 s . co m MatOfInt histSize = new MatOfInt(256); final MatOfFloat histRange = new MatOfFloat(0f, 256f); //boolean accumulate = false; Mat q_hist = new Mat(); int hist_w = 512; int hist_h = 600; long bin_w; bin_w = Math.round((double) (hist_w / 256)); Mat histImage = new Mat(hist_h, hist_w, CvType.CV_8UC3); Imgproc.calcHist(bgr_planes, new MatOfInt(0), new Mat(), q_hist, histSize, histRange); Core.normalize(q_hist, q_hist, 0, histImage.rows(), Core.NORM_MINMAX, -1, new Mat()); return q_hist; }
From source file:Retrive.java
public Mat histo(Mat imgs) { Vector<Mat> bgr_planes = new Vector<>(); Core.split(imgs, bgr_planes);//from w w w. ja v a 2s. com MatOfInt histSize = new MatOfInt(256); final MatOfFloat histRange = new MatOfFloat(0f, 256f); boolean accumulate = false; Mat b_hist = new Mat(); int hist_w = 512; int hist_h = 600; //long bin_w; //bin_w = Math.round((double) (hist_w / 256)); Mat histImage = new Mat(hist_h, hist_w, CvType.CV_8UC3); Imgproc.calcHist(bgr_planes, new MatOfInt(0), new Mat(), b_hist, histSize, histRange, accumulate); Core.normalize(b_hist, b_hist, 0, histImage.rows(), Core.NORM_MINMAX, -1, new Mat()); return b_hist; }
From source file:KoImgProc.java
License:Open Source License
/** * Takes a Mat and performs a series of image analysis and filtering steps * to detect stones in the image and filter out false circles. * @param color // www .j a va2 s. co m * The input Mat to perform analysis on. Must be a 3-channel, * 8-bit BGR color image. * @return An array of KoCircle objects that represent stones that were * detected on the board. */ public static ArrayList<KoCircle> detectStones(Mat color) { // Create 2 Mats we'll need for image processing Mat grey = new Mat(); Mat blurred = new Mat(); Imgproc.cvtColor(color, grey, Imgproc.COLOR_BGR2GRAY); // Convert to greyscale Imgproc.GaussianBlur(grey, grey, new Size(9, 9), 2, 2); Imgproc.GaussianBlur(color, blurred, new Size(9, 9), 2, 2); int widthInPixels = color.cols(); //int heightInPixels = color.cols(); // widthInPixels will be replaced by dimensions from a camera overlay that aligns with the board ArrayList<KoCircle> stones = detectStones(grey, widthInPixels / 50, widthInPixels / 30, widthInPixels / 30, CANNY_DETECTOR_THRESHOLD_HIGH); double aveRadius = getAverageRadius(stones); // Calculate more accurate inputs to HoughCircles given the average radius int minCircleRadius = (int) (0.9 * aveRadius); int maxCircleRadius = (int) (1.1 * aveRadius); int minDist = (int) (aveRadius * 1.75); stones = detectStones(grey, minCircleRadius, maxCircleRadius, minDist, CANNY_DETECTOR_THRESHOLD_MED); TreeMap<String, Double[]> colorData = getColorData(stones, blurred, grey); if (VERBOSE) { for (String key : colorData.keySet()) { Double[] current = colorData.get(key); System.out.println("Data for " + key + ":"); for (int i = 0; i < current.length; i++) { System.out.println(current[i]); } } } stones = detectStones(grey, minCircleRadius, maxCircleRadius, minDist, CANNY_DETECTOR_THRESHOLD_LOW); return filterStones(stones, colorData, aveRadius, grey, blurred); }
From source file:KoImgProc.java
License:Open Source License
/** * Detects stones in the given image and returns an array list of KoCircle objects. * @param grey greyscale Mat of the board. * @param threshold threshold value for HoughCircles * @return an ArrayList of KoCircle objects. *//*w w w .j a va 2 s . c om*/ private static ArrayList<KoCircle> detectStones(Mat grey, int minRadius, int maxRadius, int minDist, int threshold) { Mat stones = new Mat(); ArrayList<KoCircle> highThresholdStones = new ArrayList<KoCircle>(); Imgproc.HoughCircles(grey, stones, Imgproc.CV_HOUGH_GRADIENT, DP, minDist, threshold, threshold / 2, minRadius, maxRadius); for (int i = 0; i < stones.cols(); i++) { highThresholdStones.add(new KoCircle(stones.get(0, i))); } System.out.println(highThresholdStones.size() + " stones detected. minRadius: " + minRadius + "\tmaxRadius: " + maxRadius + "\tminDist: " + minDist + "\tthreshold: " + threshold); return highThresholdStones; }