List of usage examples for org.opencv.core Core bitwise_and
public static void bitwise_and(Mat src1, Mat src2, Mat dst)
From source file:Questao1.java
void and() { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); imagemBinaria();/*from w w w.j a v a 2s. c om*/ Core.bitwise_and(image1bin, image2bin, output); normalizarBinario(); Imgcodecs.imwrite("and.jpg", output); showResult("and.jpg"); }
From source file:classes.FloodFiller.java
private void fillFrom(Point seed, int lo, int up, Scalar backgroundColor, Scalar contourFillingColor) { Mat object = ObjectGenerator.extract(image, seed.x, seed.y, 10, 10); this.meanColor = Core.mean(object); Rect ccomp = new Rect(); Mat mask = Mat.zeros(image.rows() + 2, image.cols() + 2, CvType.CV_8UC1); int connectivity = 4; int newMaskVal = 255; int ffillMode = 1; int flags = connectivity + (newMaskVal << 8) + (ffillMode == 1 ? Imgproc.FLOODFILL_FIXED_RANGE : 0); Scalar newVal = new Scalar(0.299, 0.587, 0.114); Imgproc.threshold(mask, mask, 1, 128, Imgproc.THRESH_BINARY); filledArea = Imgproc.floodFill(image.clone(), mask, seed, newVal, ccomp, new Scalar(lo, lo, lo), new Scalar(up, up, up), flags); // Highgui.imwrite("mask.png", mask); ImageUtils.saveImage(mask, "mask.png", request); morphologicalImage = new Mat(image.size(), CvType.CV_8UC3); Mat element = new Mat(3, 3, CvType.CV_8U, new Scalar(1)); ArrayList<Mat> mask3 = new ArrayList<Mat>(); mask3.add(mask);/*from w w w . j a v a 2s.c o m*/ mask3.add(mask); mask3.add(mask); Core.merge(mask3, mask); // Applying morphological filters Imgproc.erode(mask, morphologicalImage, element); Imgproc.morphologyEx(morphologicalImage, morphologicalImage, Imgproc.MORPH_CLOSE, element, new Point(-1, -1), 9); Imgproc.morphologyEx(morphologicalImage, morphologicalImage, Imgproc.MORPH_OPEN, element, new Point(-1, -1), 2); Imgproc.resize(morphologicalImage, morphologicalImage, image.size()); // Highgui.imwrite("morphologicalImage.png", morphologicalImage); ImageUtils.saveImage(morphologicalImage, "morphologicalImage.png", request); List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Core.split(mask, mask3); Mat binarymorphologicalImage = mask3.get(0); Imgproc.findContours(binarymorphologicalImage.clone(), contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE); contoursImage = new Mat(image.size(), CvType.CV_8UC3, backgroundColor); int thickness = -1; // Thicknes should be lower than zero in order to drawn the filled contours Imgproc.drawContours(contoursImage, contours, -1, contourFillingColor, thickness); // Drawing all the contours found // Highgui.imwrite("allContoursImage.png", contoursImage); ImageUtils.saveImage(contoursImage, "allContoursImage.png", request); if (contours.size() > 1) { int minContourWith = 20; int minContourHeight = 20; int maxContourWith = 6400 / 2; int maxContourHeight = 4800 / 2; contours = filterContours(contours, minContourWith, minContourHeight, maxContourWith, maxContourHeight); } if (contours.size() > 0) { 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[] points = biggestContour.toArray(); path = "M " + (int) points[0].x + " " + (int) points[0].y + " "; for (int i = 1; i < points.length; ++i) { Point v = points[i]; path += "L " + (int) v.x + " " + (int) v.y + " "; } path += "Z"; biggestContourImage = new Mat(image.size(), CvType.CV_8UC3, backgroundColor); Imgproc.drawContours(biggestContourImage, contours, 0, contourFillingColor, thickness); // Highgui.imwrite("biggestContourImage.png", biggestContourImage); ImageUtils.saveImage(biggestContourImage, "biggestContourImage.png", request); Mat maskForColorExtraction = biggestContourImage.clone(); if (isWhite(backgroundColor)) { Imgproc.dilate(maskForColorExtraction, maskForColorExtraction, new Mat(), new Point(-1, -1), 3); } else { Imgproc.erode(maskForColorExtraction, maskForColorExtraction, new Mat(), new Point(-1, -1), 3); } // Highgui.imwrite("maskForColorExtraction.png", maskForColorExtraction); ImageUtils.saveImage(maskForColorExtraction, "maskForColorExtraction.png", request); Mat extractedColor = new Mat(); if (isBlack(backgroundColor) && isWhite(contourFillingColor)) { Core.bitwise_and(maskForColorExtraction, image, extractedColor); } else { Core.bitwise_or(maskForColorExtraction, image, extractedColor); } // Highgui.imwrite("extractedColor.png", extractedColor); ImageUtils.saveImage(extractedColor, "extractedColor.png", request); computedSearchWindow = Imgproc.boundingRect(biggestContour); topLeftCorner = computedSearchWindow.tl(); Rect croppingRect = new Rect(computedSearchWindow.x, computedSearchWindow.y, computedSearchWindow.width - 1, computedSearchWindow.height - 1); Mat imageForTextRecognition = new Mat(extractedColor.clone(), croppingRect); // Highgui.imwrite(outImageName, imageForTextRecognition); ImageUtils.saveImage(imageForTextRecognition, outImageName, request); // // // Mat data = new Mat(imageForTextRecognition.size(), CvType.CV_8UC3, backgroundColor); // imageForTextRecognition.copyTo(data); // data.convertTo(data, CvType.CV_8UC3); // // // The meanColor variable represents the color in the GBR space, the following line transforms this to the RGB color space, which // // is assumed in the prepareImage method of the TextRecognitionPreparer class // Scalar userColor = new Scalar(meanColor.val[2], meanColor.val[1], meanColor.val[0]); // // ArrayList<String> recognizableImageNames = TextRecognitionPreparer.generateRecognizableImagesNames(data, backgroundColor, userColor); // for (String imageName : recognizableImageNames) { // // try { // // First recognition step // String recognizedText = TextRecognizer.recognize(imageName, true).trim(); // if (recognizedText != null && !recognizedText.isEmpty()) { // recognizedStrings.add(recognizedText); // } // // Second recognition step // recognizedText = TextRecognizer.recognize(imageName, false).trim(); // if (recognizedText != null && !recognizedText.isEmpty()) { // recognizedStrings.add(recognizedText); // } // // } catch (Exception e) { // } // } // //// ArrayList<BufferedImage> recognizableBufferedImages = TextRecognitionPreparer.generateRecognizableBufferedImages(data, backgroundColor, userColor); //// for (BufferedImage bufferedImage : recognizableBufferedImages) { //// try { //// // First recognition step //// String recognizedText = TextRecognizer.recognize(bufferedImage, true).trim(); //// if (recognizedText != null && !recognizedText.isEmpty()) { //// recognizedStrings.add(recognizedText); //// } //// // Second recognition step //// recognizedText = TextRecognizer.recognize(bufferedImage, false).trim(); //// if (recognizedText != null && !recognizedText.isEmpty()) { //// recognizedStrings.add(recognizedText); //// } //// //// } catch (Exception e) { //// } //// } // // // // compute all moments Moments mom = Imgproc.moments(biggestContour); massCenter = new Point(mom.get_m10() / mom.get_m00(), mom.get_m01() / mom.get_m00()); // draw black dot Core.circle(contoursImage, massCenter, 4, contourFillingColor, 8); } }
From source file:classes.ObjectFinder.java
private void backprojectObjectHistogram() { // Converting the current fram to HSV color space Mat hsvImage = new Mat(this.objectImage.size(), CvType.CV_8UC3); Imgproc.cvtColor(this.inputFrame, hsvImage, Imgproc.COLOR_BGR2HSV); // Getting the pixels that are in te specified ranges int hmin = this.thresholdsVector.get(0); int hmax = this.thresholdsVector.get(1); int smin = this.thresholdsVector.get(2); int smax = this.thresholdsVector.get(3); int vmin = this.thresholdsVector.get(4); int vmax = this.thresholdsVector.get(5); Mat maskImage = new Mat(this.objectImage.size(), CvType.CV_8UC1); Core.inRange(hsvImage, new Scalar(hmin, smin, vmin), new Scalar(hmax, smax, vmax), maskImage); // Taking the hue channel of the image Mat hueImage = new Mat(hsvImage.size(), hsvImage.depth()); MatOfInt fromto = new MatOfInt(0, 0); Core.mixChannels(Arrays.asList(hsvImage), Arrays.asList(hueImage), fromto); // Backprojecting the histogram over that hue channel image MatOfFloat ranges = new MatOfFloat(0, 180); MatOfInt channels = new MatOfInt(0); Imgproc.calcBackProject(Arrays.asList(hueImage), channels, this.objectHistogram, this.backprojectionImage, ranges, 1);/*w ww . j a v a2s. c o m*/ Core.bitwise_and(backprojectionImage, maskImage, backprojectionImage); }
From source file:com.astrocytes.core.operationsengine.CoreOperations.java
License:Open Source License
public static Mat and(Mat first, Mat second) { Mat dest = new Mat(); Core.bitwise_and(first, second, dest); return dest; }
From source file:com.mitzuli.core.ocr.OcrPreprocessor.java
License:Open Source License
/** * Binarizes and cleans the input image for OCR, saving debugging images in the given directory. * * @param input the input image, which is recycled by this method, so the caller should make a defensive copy of it if necessary. * @param debugDir the directory to write the debugging images to, or null to disable debugging. * @return the preprocessed image.//w ww . j a v a 2 s. c o m */ static Image preprocess(final Image input, final File debugDir) { // TODO Temporary workaround to allow to manually enable debugging (the global final variable should be used) boolean DEBUG = debugDir != null; // Initialization final Mat mat = input.toGrayscaleMat(); final Mat debugMat = DEBUG ? input.toRgbMat() : null; input.recycle(); final Mat aux = new Mat(mat.size(), CvType.CV_8UC1); final Mat binary = new Mat(mat.size(), CvType.CV_8UC1); if (DEBUG) Image.fromMat(mat).write(new File(debugDir, "1_input.jpg")); // Binarize the input image in mat through adaptive Gaussian thresholding Imgproc.adaptiveThreshold(mat, binary, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 51, 13); // Imgproc.adaptiveThreshold(mat, binary, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 31, 7); // Edge detection Imgproc.morphologyEx(mat, mat, Imgproc.MORPH_OPEN, KERNEL_3X3); // Open Imgproc.morphologyEx(mat, aux, Imgproc.MORPH_CLOSE, KERNEL_3X3); // Close Core.addWeighted(mat, 0.5, aux, 0.5, 0, mat); // Average Imgproc.morphologyEx(mat, mat, Imgproc.MORPH_GRADIENT, KERNEL_3X3); // Gradient Imgproc.threshold(mat, mat, 0, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU); // Edge map if (DEBUG) Image.fromMat(mat).write(new File(debugDir, "2_edges.jpg")); // Extract word level connected-components from the dilated edge map Imgproc.dilate(mat, mat, KERNEL_3X3); if (DEBUG) Image.fromMat(mat).write(new File(debugDir, "3_dilated_edges.jpg")); final List<MatOfPoint> wordCCs = new ArrayList<MatOfPoint>(); Imgproc.findContours(mat, wordCCs, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); // Filter word level connected-components individually and calculate their average attributes final List<MatOfPoint> individuallyFilteredWordCCs = new ArrayList<MatOfPoint>(); final List<MatOfPoint> removedWordCCs = new ArrayList<MatOfPoint>(); double avgWidth = 0, avgHeight = 0, avgArea = 0; for (MatOfPoint cc : wordCCs) { final Rect boundingBox = Imgproc.boundingRect(cc); if (boundingBox.height >= 6 // bounding box height >= 6 && boundingBox.area() >= 50 // bounding box area >= 50 && (double) boundingBox.width / (double) boundingBox.height >= 0.25 // bounding box aspect ratio >= 1:4 && boundingBox.width <= 0.75 * mat.width() // bounding box width <= 0.75 image width && boundingBox.height <= 0.75 * mat.height()) // bounding box height <= 0.75 image height { individuallyFilteredWordCCs.add(cc); avgWidth += boundingBox.width; avgHeight += boundingBox.height; avgArea += boundingBox.area(); } else { if (DEBUG) removedWordCCs.add(cc); } } wordCCs.clear(); avgWidth /= individuallyFilteredWordCCs.size(); avgHeight /= individuallyFilteredWordCCs.size(); avgArea /= individuallyFilteredWordCCs.size(); if (DEBUG) { Imgproc.drawContours(debugMat, removedWordCCs, -1, BLUE, -1); removedWordCCs.clear(); } // Filter word level connected-components in relation to their average attributes final List<MatOfPoint> filteredWordCCs = new ArrayList<MatOfPoint>(); for (MatOfPoint cc : individuallyFilteredWordCCs) { final Rect boundingBox = Imgproc.boundingRect(cc); if (boundingBox.width >= 0.125 * avgWidth // bounding box width >= 0.125 average width && boundingBox.width <= 8 * avgWidth // bounding box width <= 8 average width && boundingBox.height >= 0.25 * avgHeight // bounding box height >= 0.25 average height && boundingBox.height <= 4 * avgHeight) // bounding box height <= 4 average height { filteredWordCCs.add(cc); } else { if (DEBUG) removedWordCCs.add(cc); } } individuallyFilteredWordCCs.clear(); if (DEBUG) { Imgproc.drawContours(debugMat, filteredWordCCs, -1, GREEN, -1); Imgproc.drawContours(debugMat, removedWordCCs, -1, PURPLE, -1); removedWordCCs.clear(); } // Extract paragraph level connected-components mat.setTo(BLACK); Imgproc.drawContours(mat, filteredWordCCs, -1, WHITE, -1); final List<MatOfPoint> paragraphCCs = new ArrayList<MatOfPoint>(); Imgproc.morphologyEx(mat, aux, Imgproc.MORPH_CLOSE, KERNEL_30X30); Imgproc.findContours(aux, paragraphCCs, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); // Filter paragraph level connected-components according to the word level connected-components inside final List<MatOfPoint> textCCs = new ArrayList<MatOfPoint>(); for (MatOfPoint paragraphCC : paragraphCCs) { final List<MatOfPoint> wordCCsInParagraphCC = new ArrayList<MatOfPoint>(); aux.setTo(BLACK); Imgproc.drawContours(aux, Collections.singletonList(paragraphCC), -1, WHITE, -1); Core.bitwise_and(mat, aux, aux); Imgproc.findContours(aux, wordCCsInParagraphCC, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); final Rect boundingBox = Imgproc.boundingRect(paragraphCC); final double center = mat.size().width / 2; final double distToCenter = center > boundingBox.x + boundingBox.width ? center - boundingBox.x - boundingBox.width : center < boundingBox.x ? boundingBox.x - center : 0.0; if (DEBUG) { System.err.println("****************************************"); System.err.println("\tArea: " + boundingBox.area()); System.err.println("\tDistance to center: " + distToCenter); System.err.println("\tCCs inside: " + wordCCsInParagraphCC.size()); } if ((wordCCsInParagraphCC.size() >= 10 || wordCCsInParagraphCC.size() >= 0.3 * filteredWordCCs.size()) && mat.size().width / distToCenter >= 4) { textCCs.addAll(wordCCsInParagraphCC); if (DEBUG) { System.err.println("\tText: YES"); Imgproc.drawContours(debugMat, Collections.singletonList(paragraphCC), -1, DARK_GREEN, 5); } } else { if (DEBUG) { System.err.println("\tText: NO"); Imgproc.drawContours(debugMat, Collections.singletonList(paragraphCC), -1, DARK_RED, 5); } } } filteredWordCCs.clear(); paragraphCCs.clear(); mat.setTo(WHITE); Imgproc.drawContours(mat, textCCs, -1, BLACK, -1); textCCs.clear(); if (DEBUG) Image.fromMat(debugMat).write(new File(debugDir, "4_filtering.jpg")); // Obtain the final text mask from the filtered connected-components Imgproc.erode(mat, mat, KERNEL_15X15); Imgproc.morphologyEx(mat, mat, Imgproc.MORPH_OPEN, KERNEL_30X30); if (DEBUG) Image.fromMat(mat).write(new File(debugDir, "5_text_mask.jpg")); // Apply the text mask to the binarized image if (DEBUG) Image.fromMat(binary).write(new File(debugDir, "6_binary.jpg")); binary.setTo(WHITE, mat); if (DEBUG) Image.fromMat(binary).write(new File(debugDir, "7_binary_text.jpg")); // Dewarp the text using Leptonica Pix pixs = Image.fromMat(binary).toGrayscalePix(); Pix pixsDewarp = Dewarp.dewarp(pixs, 0, Dewarp.DEFAULT_SAMPLING, 5, true); final Image result = Image.fromGrayscalePix(pixsDewarp); if (DEBUG) result.write(new File(debugDir, "8_dewarp.jpg")); // Clean up pixs.recycle(); mat.release(); aux.release(); binary.release(); if (debugMat != null) debugMat.release(); return result; }
From source file:ctPrincipal.Operacoes.java
String realizarOperacoes(int op) { String resultImgOutput = ""; switch (op) { case 1://and imagemBinaria();//from ww w .j a v a 2s. c o m Core.bitwise_and(image1bin, image2bin, output); normalizarBinario(); Imgcodecs.imwrite("OutputImg/and.jpg", output); resultImgOutput = "OutputImg/and.jpg"; break; case 2://or imagemBinaria(); Core.bitwise_or(image1bin, image2bin, output); normalizarBinario(); Imgcodecs.imwrite("OutputImg/or.jpg", output); resultImgOutput = "OutputImg/or.jpg"; break; case 3://xor imagemBinaria(); Core.bitwise_xor(image1bin, image2bin, output); normalizarBinario(); Imgcodecs.imwrite("OutputImg/xor.jpg", output); resultImgOutput = "OutputImg/xor.jpg"; break; case 4://not Core.bitwise_not(image1bin, output); Imgcodecs.imwrite("OutputImg/not.jpg", output); resultImgOutput = "OutputImg/not.jpg"; break; case 5://soma Core.add(image1, image2, output); Imgcodecs.imwrite("OutputImg/soma.jpg", output); resultImgOutput = "OutputImg/soma.jpg"; break; case 6://subtracao Core.subtract(image1, image2, output); Imgcodecs.imwrite("OutputImg/subtracao.jpg", output); resultImgOutput = "OutputImg/subtracao.jpg"; break; case 7:// multiplicacao Core.multiply(image1, image2, output); Imgcodecs.imwrite("OutputImg/multiplicacao.jpg", output); resultImgOutput = "OutputImg/multiplicacao.jpg"; break; case 8://divisao Core.divide(image1, image2, output); Imgcodecs.imwrite("OutputImg/divisao.jpg", output); resultImgOutput = "OutputImg/divisao.jpg"; break; } return resultImgOutput; }
From source file:imageprocess.ObjectFinder.java
public static void main(String[] args) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); Mat image = Highgui.imread("D:\\backup\\opencv\\baboon1.jpg"); // Define ROI Rect rect = new Rect(110, 260, 35, 40); Mat imageROI = new Mat(image, rect); Core.rectangle(image, new Point(110, 260), new Point(145, 300), new Scalar(0, 0, 255)); Imshow origIm = new Imshow("Origin"); origIm.showImage(image);// w ww .j a v a 2s . co m ObjectFinder finder = new ObjectFinder(false, 0.2f); // Get the Hue histogram int minSat = 65; Mat hist = finder.getHueHistogram(imageROI, minSat); Mat norm = new Mat(); Core.normalize(hist, norm, 1, 0, NORM_L2); finder.setROIHistogram(norm); // Convert to HSV space Mat hsv = new Mat(); Imgproc.cvtColor(image, hsv, CV_BGR2HSV); // Split the image List<Mat> v = new ArrayList<>(); Core.split(hsv, v); // Eliminate pixels with low saturation Imgproc.threshold(v.get(1), v.get(1), minSat, 255, THRESH_BINARY); Imshow satIm = new Imshow("Saturation"); satIm.showImage(v.get(1)); // Get back-projection of hue histogram Mat result = finder.find(hsv, new MatOfInt(0), new MatOfFloat(0.0f, 180.0f)); Imshow resultHueIm = new Imshow("Result Hue"); resultHueIm.showImage(result); Core.bitwise_and(result, v.get(1), result); Imshow resultHueAndIm = new Imshow("Result Hue and raw"); resultHueAndIm.showImage(result); // Second image Mat image2 = Highgui.imread("D:\\backup\\opencv\\baboon3.jpg"); // Display image Imshow img2Im = new Imshow("Imgage2"); img2Im.showImage(image2); // Convert to HSV space Imgproc.cvtColor(image2, hsv, CV_BGR2HSV); // Split the image Core.split(hsv, v); // Eliminate pixels with low saturation Imgproc.threshold(v.get(1), v.get(1), minSat, 255, THRESH_BINARY); Imshow satIm2 = new Imshow("Saturation2"); satIm2.showImage(v.get(1)); // Get back-projection of hue histogram finder.setThreshold(-1.0f); result = finder.find(hsv, new MatOfInt(0), new MatOfFloat(0.0f, 180.0f)); Imshow resultHueIm2 = new Imshow("Result Hue2"); resultHueIm2.showImage(result); Core.bitwise_and(result, v.get(1), result); Imshow resultHueAndIm2 = new Imshow("Result Hue and raw2"); resultHueAndIm2.showImage(result); Rect rect2 = new Rect(110, 260, 35, 40); Core.rectangle(image2, new Point(110, 260), new Point(145, 300), new Scalar(0, 0, 255)); TermCriteria criteria = new TermCriteria(TermCriteria.MAX_ITER | TermCriteria.EPS, 100, 0.01); int steps = Video.meanShift(result, rect2, criteria); Core.rectangle(image2, new Point(rect2.x, rect2.y), new Point(rect2.x + rect2.width, rect2.y + rect2.height), new Scalar(0, 255, 0)); Imshow meanshiftIm = new Imshow("Meanshift result"); meanshiftIm.showImage(image2); }
From source file:nz.ac.auckland.lablet.vision.CamShiftTracker.java
License:Open Source License
/** * Gets the location of an object in a frame. Assumes you have called setRegionOfInterest, * which informs CamShiftTracker which object to track. * * @param frame The frame to search for the object in. * @return The location and bounds of the object, represented by a Rect. *///from ww w . ja va 2s .co m public Rect getObjectLocation(Bitmap frame) { Mat image = new Mat(); Utils.bitmapToMat(frame, image); // Mat out = new Mat(image.rows(), image.cols(), image.type()); // image.convertTo(out, -1, 2.0, 2.0); // image = out; toHsv(image, hsvMin, hsvMax); ArrayList<Mat> hsvs = new ArrayList<>(); hsvs.add(hsv); Imgproc.calcBackProject(hsvs, new MatOfInt(0), hist, backproj, ranges, 1); Core.bitwise_and(backproj, mask, backproj); try { Rect tempTrackWindow = trackWindow.clone(); RotatedRect result = Video.CamShift(backproj, trackWindow, termCriteria); if (result.size.equals(new Size(0, 0)) && result.angle == 0 && result.center.equals(new Point(0, 0))) { trackWindow = tempTrackWindow; return null; } } catch (Exception e) { Log.e(TAG, "Shit went down: ", e); return null; } return trackWindow.clone(); }
From source file:opencv.fark.VideoSecMainFrame.java
private void jButtonKarsilastirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonKarsilastirActionPerformed if (referans_degeri == 1) { t1 = new Thread() { @Override// w w w .j a v a2 s. c o m public void run() { try { while (!interrupted()) { //System.out.println("Karlatr"); Rect r = new Rect(staticFirstPoint, staticSecondPoint); temp = frame.submat(r); jPanel2.repaint(); MatToBufImg matToBufImage = new MatToBufImg(); matToBufImage.setMatrix(temp, ".png"); g1.drawImage(matToBufImage.getBufferedImage(), jPanel2.getWidth() / 2 - reference_section.cols() / 2, jPanel2.getHeight() / 2 - reference_section.rows() / 2, null); //Highgui.imwrite("D:\\resim1.jpg", temp); //metod 3 sn yede bir fark hesapla theDifferenceBetweenTheTwoImages(reference_section, temp); Thread.sleep(3000); } } catch (InterruptedException ex) { ex.printStackTrace(); } } private void theDifferenceBetweenTheTwoImages(Mat ref, Mat tem) { Mat sonuc = new Mat(tem.rows(), tem.cols(), CvType.CV_8UC1); Mat gray1 = new Mat(tem.rows(), tem.cols(), CvType.CV_8UC1); Mat gray2 = new Mat(reference_section.rows(), reference_section.cols(), CvType.CV_8UC1); Imgproc.cvtColor(tem, gray1, Imgproc.COLOR_BGR2GRAY); Imgproc.cvtColor(ref, gray2, Imgproc.COLOR_BGR2GRAY); MatToBufImg matToBufImage = new MatToBufImg(); // matToBufImage.setMatrix(gray2, ".jpg"); // g1.drawImage(matToBufImage.getBufferedImage(), 0, 0, null); // // matToBufImage.setMatrix(gray1, ".jpg"); // g1.drawImage(matToBufImage.getBufferedImage(), 0, 0, null); Core.absdiff(gray2, gray1, sonuc); Imgproc.blur(sonuc, sonuc, new Size(15, 15)); Imgproc.threshold(sonuc, sonuc, 2, 255, Imgproc.THRESH_BINARY); Imgproc.dilate(sonuc, sonuc, element); Imgproc.erode(sonuc, sonuc, element); // List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); int sayac = 0; float boyut = sonuc.cols() * sonuc.rows(); for (int i = 0; i < sonuc.cols(); i++) { for (int j = 0; j < sonuc.rows(); j++) { double a[] = sonuc.get(j, i); if (a[0] == 255) { sayac++; } } } float hata = (sayac / boyut) * 100; System.out.println("Bozukluk oran % :" + hata); if (hata == 0) { list1.add("Hatasiz!", 0); Highgui.imwrite("D:\\testResim\\hatasiz\\ref" + (++say) + ".png", tem); } else { list1.add("%" + String.valueOf(hata).substring(0, 5), 0); Highgui.imwrite("D:\\testResim\\hatali\\yuzde" + String.valueOf(hata).substring(0, 2) + "bozuk" + (++say) + ".png", tem); } Imgproc.cvtColor(sonuc, sonuc, Imgproc.COLOR_GRAY2BGR); Core.bitwise_and(sonuc, tem, sonuc); matToBufImage.setMatrix(sonuc, ".png"); g1.drawImage(matToBufImage.getBufferedImage(), jPanel2.getWidth() / 2 - reference_section.cols() / 2, jPanel2.getHeight() / 2 - reference_section.rows() / 2, null); // Highgui.imwrite("D:\\farkResim.jpg",sonuc); } }; t1.start(); } else { jLabel1.setForeground(Color.red); jLabel1.setOpaque(true); jLabel1.setBackground(Color.black); jLabel1.setFont(new Font("Serif", Font.PLAIN, 20)); jLabel1.setText("Referans Resim Seiniz!"); } }
From source file:simeav.filtros.instanciaciones.DetectorConectoresEstandar.java
@Override public Mat detectarConectores(Mat original, Mat mascaraModulos, Diagrama diagrama) { Mat sinCuadrados = Utils.borrarMascara(original, mascaraModulos); // dilato los conectores para que se superpongan con los cuadrados sinCuadrados = Utils.dilate(sinCuadrados); sinCuadrados = Utils.dilate(sinCuadrados); sinCuadrados = Utils.dilate(sinCuadrados); //elimino puntos que pueden haber quedado de la eliminacion de cuadrados ArrayList<MatOfPoint> contornos = Utils.detectarContornos(sinCuadrados); for (int i = 0; i < contornos.size(); i++) { double area = Imgproc.contourArea(contornos.get(i)); if (area <= 50) { Imgproc.drawContours(sinCuadrados, contornos, i, new Scalar(0, 0, 0), -1); }/*from w w w. j a va 2 s.c o m*/ } this.extremos = original.clone(); Mat mascara; String tipo_extremo1, tipo_extremo2; // Imagen en la que se va a dibuja el resultado Mat conectores = Mat.zeros(sinCuadrados.size(), CvType.CV_8UC3); Mat contorno; contornos = Utils.detectarContornos(sinCuadrados); Mat intersec = new Mat(); ArrayList<MatOfPoint> contornos_intersec; int r, g, b; for (int j = contornos.size() - 1; j >= 0; j--) { //Dibujo el contorno relleno, para despues sacar la interseccion con los cuadrados contorno = Mat.zeros(sinCuadrados.size(), CvType.CV_8UC3); Imgproc.drawContours(contorno, contornos, j, new Scalar(180, 255, 255), -1); Imgproc.cvtColor(contorno, contorno, Imgproc.COLOR_BGR2GRAY); //Calculo la interseccion con los cuadrados (se dibujan en intersec) Core.bitwise_and(contorno, mascaraModulos, intersec); //Saco los contornos de las intersecciones para saber donde estan contornos_intersec = Utils.detectarContornos(intersec); if (contornos_intersec.size() > 1) { Scalar color = Utils.getColorRandom(); for (int z = 0; z < contornos_intersec.size(); z++) { Imgproc.drawContours(conectores, contornos_intersec, z, color, -1); } ArrayList<Point> centros_extremos = Utils.getCentros(contornos_intersec); for (Point centros_extremo : centros_extremos) { Core.circle(conectores, centros_extremo, 4, color, -1); } analizarExtremos(j, centros_extremos, diagrama); Conector c = diagrama.getConector(j); Core.rectangle(conectores, c.getModuloDesde().getRectangulo().tl(), c.getModuloDesde().getRectangulo().br(), color, 3); Core.rectangle(conectores, c.getModuloHasta().getRectangulo().tl(), c.getModuloHasta().getRectangulo().br(), color, 3); Point tl_desde = new Point(c.getDesde().x - 20, c.getDesde().y - 20); Point br_desde = new Point(c.getDesde().x + 20, c.getDesde().y + 20); Point tl_hasta = new Point(c.getHasta().x - 20, c.getHasta().y - 20); Point br_hasta = new Point(c.getHasta().x + 20, c.getHasta().y + 20); mascara = new Mat(sinCuadrados.size(), CvType.CV_8U, new Scalar(255, 255, 255)); Core.rectangle(mascara, tl_desde, br_desde, new Scalar(0, 0, 0), -1); tipo_extremo1 = clasificarExtremo(Utils.borrarMascara(original, mascara)); mascara = new Mat(sinCuadrados.size(), CvType.CV_8U, new Scalar(255, 255, 255)); Core.rectangle(mascara, tl_hasta, br_hasta, new Scalar(0, 0, 0), -1); tipo_extremo2 = clasificarExtremo(Utils.borrarMascara(original, mascara)); if (!tipo_extremo1.equals(tipo_extremo2)) { if (tipo_extremo1.equals("Normal")) c.setTipo(tipo_extremo2); else if (tipo_extremo2.equals("Normal")) { Modulo aux = c.getModuloDesde(); c.setDesde(c.getModuloHasta()); c.setHacia(aux); Point p_aux = c.getDesde(); c.setDesde(c.getHasta()); c.setHasta(p_aux); c.setTipo(tipo_extremo1); } else { c.setTipo("Indeterminado"); } } else { c.setTipo("Indeterminado"); } } } return conectores; }