public static void main(String[] args) throws Exception{ FlashUtil.setLog(log); log.log("Loading settings and properties...", "Dashboard"); validateBasicHierarcy(); loadSettings(); validateBasicSettings(); printSettings(); log.log("Done", "Dashboard"); setupValuePath(); log.log("FlashLib version: "+FlashUtil.VERSION, "Dashboard"); log.log("Loading opencv natives: "+Core.NATIVE_LIBRARY_NAME+" ...", "Dashboard"); loadValueLibrary(Core.NATIVE_LIBRARY_NAME); log.log("opencv version: "+Core.VERSION, "Dashboard"); log.log("Creating shutdown hook...", "Dashboard"); Runtime.getRuntime().addShutdownHook(new Thread(()->close())); log.log("Done", "Dashboard"); log.save(); initStart(); log.log("Launching FX...", "Dashboard"); launch(); }
public void run() { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); String base = "C:/Books in Progress/Java for Data Science/Chapter 10/OpenCVExamples/src/resources"; CascadeClassifier faceDetector = new CascadeClassifier(base + "/lbpcascade_frontalface.xml"); Mat image = Imgcodecs.imread(base + "/images.jpg"); MatOfRect faceVectors = new MatOfRect(); faceDetector.detectMultiScale(image, faceVectors); out.println(faceVectors.toArray().length + " faces found"); for (Rect rect : faceVectors.toArray()) { Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0)); } Imgcodecs.imwrite("faceDetection.png", image); }
public static void staticFace(String input, String output) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); System.out.println("\nRunning FaceDetector"); final CascadeClassifier faceDetector = new CascadeClassifier(StaticFacialRecognition.class .getResource("../../../../../opencv/sources/data/haarcascades_cuda/haarcascade_frontalface_alt.xml") .getPath().substring(1)); final Mat image = Imgcodecs.imread(input); // �������� StaticFacialRecognition.class.getResource(input).getPath().substring(1) final MatOfRect faceDetections = new MatOfRect(); faceDetector.detectMultiScale(image, faceDetections); System.out.println(String.format("Detected %s faces", faceDetections.toArray().length)); for (final Rect rect : faceDetections.toArray()) { Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0)); } System.out.println(String.format("Writing %s", output)); Imgcodecs.imwrite(output, image); // �������� StaticFacialRecognition.class.getResource("").getPath().substring(1) + // output }
public void sharpenImage() { String fileName = "SharpnessExample2.png"; fileName = "smoothCat.jpg"; fileName = "blurredText.jpg"; fileName = "Blurred Text3.jpg"; try { // Not working that well !!! Mat source = Imgcodecs.imread(fileName, // Imgcodecs.CV_LOAD_IMAGE_COLOR); Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE); Mat destination = new Mat(source.rows(), source.cols(), source.type()); Imgproc.GaussianBlur(source, destination, new Size(0, 0), 10); // The following was used witht he cat // Core.addWeighted(source, 1.5, destination, -0.75, 0, destination); // Core.addWeighted(source, 2.5, destination, -1.5, 0, destination); Core.addWeighted(source, 1.5, destination, -0.75, 0, destination); Imgcodecs.imwrite("sharpenedCat.jpg", destination); } catch (Exception ex) { ex.printStackTrace(); } }
/** * Apply padding to the image. */ private Mat imagePadding(Mat source, int blockSize) { int width = source.width(); int height = source.height(); int bottomPadding = 0; int rightPadding = 0; if (width % blockSize != 0) { bottomPadding = blockSize - (width % blockSize); } if (height % blockSize != 0) { rightPadding = blockSize - (height % blockSize); } Core.copyMakeBorder(source, source, 0, bottomPadding, 0, rightPadding, Core.BORDER_CONSTANT, Scalar.all(0)); return source; }
/** * Gets the average color of the object * * @param img The image matrix, of any color size * @param imgSpace The image's color space * @return The average color of the region */ public Color averageColor(Mat img, ColorSpace imgSpace) { //Coerce values to stay within screen dimensions double leftX = MathUtil.coerce(0, img.cols() - 1, left()); double rightX = MathUtil.coerce(0, img.cols() - 1, right()); double topY = MathUtil.coerce(0, img.rows() - 1, top()); double bottomY = MathUtil.coerce(0, img.rows() - 1, bottom()); //Input points into array for calculation //TODO rectangular submatrix-based calculation isn't perfectly accurate when you have ellipses or weird shapes Mat subMat = img.submat((int) topY, (int) bottomY, (int) leftX, (int) rightX); //Calculate average and return new color instance return Color.create(Core.mean(subMat), imgSpace); }
private static Mat[] applyCLAHE(Mat img, Mat L) { Mat[] result = new Mat[2]; CLAHE clahe = Imgproc.createCLAHE(); clahe.setClipLimit(2.0); Mat L2 = new Mat(); clahe.apply(L, L2); Mat LabIm2 = new Mat(); List<Mat> lab = new ArrayList<Mat>(); Core.split(img, lab); Core.merge(new ArrayList<Mat>(Arrays.asList(L2, lab.get(1), lab.get(2))), LabIm2); Mat img2 = new Mat(); Imgproc.cvtColor(LabIm2, img2, Imgproc.COLOR_Lab2BGR); result[0] = img2; result[1] = L2; return result; }
@Override public void process(Mat input, Mat mask) { Imgproc.cvtColor(input,input,Imgproc.COLOR_RGB2HSV_FULL); Imgproc.GaussianBlur(input,input,new Size(3,3),0); Scalar lower = new Scalar(perfect.val[0] - range.val[0], perfect.val[1] - range.val[1],perfect.val[2] - range.val[2]); Scalar upper = new Scalar(perfect.val[0] + range.val[0], perfect.val[1] + range.val[1],perfect.val[2] + range.val[2]); Core.inRange(input,lower,upper,mask); input.release(); }
public static void main(String args[]) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); CascadeClassifier faceCascade = new CascadeClassifier(xmlFile); if(!faceCascade.load(xmlFile)) { System.out.println("Error Loading XML File"); } else { System.out.println("Success Loading XML"); } //invokeLater enables *swing threads to operate, //it is not actually going to run this method later EventQueue.invokeLater(new Runnable() { public void run() { try { FaceTrackMain frame = new FaceTrackMain(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); }
private float[] getInputDataLeNet(Bitmap bitmap) { final int INPUT_LENGTH = 28; Mat imageMat = new Mat(); Mat inputMat = new Mat(); Utils.bitmapToMat(bitmap, imageMat); // convert the image to 28 * 28, grayscale, 0~1, and smaller means whiter Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_RGBA2GRAY); imageMat = centerCropAndScale(imageMat, INPUT_LENGTH); imageMat.convertTo(imageMat, CvType.CV_32F, 1. / 255); Core.subtract(Mat.ones(imageMat.size(), CvType.CV_32F), imageMat, inputMat); float[] inputData = new float[inputMat.width() * inputMat.height()]; inputMat.get(0, 0, inputData); return inputData; }
public static Mat transEstimate(Mat img, int patchSz, double[] airlight, double lambda, double fTrans, int r, double eps, double gamma) { int rows = img.rows(); int cols = img.cols(); List<Mat> bgr = new ArrayList<>(); Core.split(img, bgr); int type = bgr.get(0).type(); // calculate the transmission map Mat T = computeTrans(img, patchSz, rows, cols, type, airlight, lambda, fTrans); // refine the transmission map img.convertTo(img, CvType.CV_8UC1); Mat gray = new Mat(); Imgproc.cvtColor(img, gray, Imgproc.COLOR_BGR2GRAY); gray.convertTo(gray, CvType.CV_32F); Core.divide(gray, new Scalar(255.0), gray); T = Filters.GuidedImageFilter(gray, T, r, eps); Mat Tsmooth = new Mat(); Imgproc.GaussianBlur(T, Tsmooth, new Size(81, 81), 40); Mat Tdetails = new Mat(); Core.subtract(T, Tsmooth, Tdetails); Core.multiply(Tdetails, new Scalar(gamma), Tdetails); Core.add(Tsmooth, Tdetails, T); return T; }
static Mat drawMatches(Mat img1, MatOfKeyPoint key1, Mat img2, MatOfKeyPoint key2, MatOfDMatch matches, boolean imageOnly){ //https://github.com/mustafaakin/image-matcher/tree/master/src/in/mustafaak/imagematcher Mat out = new Mat(); Mat im1 = new Mat(); Mat im2 = new Mat(); Imgproc.cvtColor(img1, im1, Imgproc.COLOR_GRAY2RGB); Imgproc.cvtColor(img2, im2, Imgproc.COLOR_GRAY2RGB); if ( imageOnly){ MatOfDMatch emptyMatch = new MatOfDMatch(); MatOfKeyPoint emptyKey1 = new MatOfKeyPoint(); MatOfKeyPoint emptyKey2 = new MatOfKeyPoint(); Features2d.drawMatches(im1, emptyKey1, im2, emptyKey2, emptyMatch, out); } else { Features2d.drawMatches(im1, key1, im2, key2, matches, out); } //Bitmap bmp = Bitmap.createBitmap(out.cols(), out.rows(), Bitmap.Config.ARGB_8888); Imgproc.cvtColor(out, out, Imgproc.COLOR_BGR2RGB); Imgproc.putText(out, "Frame", new Point(img1.width() / 2,30), Core.FONT_HERSHEY_PLAIN, 2, new Scalar(0,255,255),3); Imgproc.putText(out, "Match", new Point(img1.width() + img2.width() / 2,30), Core.FONT_HERSHEY_PLAIN, 2, new Scalar(255,0,0),3); return out; }
public static Mat LocalContrast(Mat img) { double[] h = { 1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0 }; Mat mask = new Mat(h.length, h.length, img.type()); for (int i = 0; i < h.length; i++) { for (int j = 0; j < h.length; j++) { mask.put(i, j, h[i] * h[j]); } } Mat localContrast = new Mat(); Imgproc.filter2D(img, localContrast, img.depth(), mask); for (int i = 0; i < localContrast.rows(); i++) { for (int j = 0; j < localContrast.cols(); j++) { if (localContrast.get(i, j)[0] > Math.PI / 2.75) localContrast.put(i, j, Math.PI / 2.75); } } Core.subtract(img, localContrast, localContrast); return localContrast.mul(localContrast); }
public static Mat LuminanceWeight(Mat img, Mat L) { Mat bCnl = new Mat(); Core.extractChannel(img, bCnl, 0); bCnl.convertTo(bCnl, CvType.CV_32F); Mat gCnl = new Mat(); Core.extractChannel(img, gCnl, 1); gCnl.convertTo(gCnl, CvType.CV_32F); Mat rCnl = new Mat(); Core.extractChannel(img, rCnl, 2); rCnl.convertTo(rCnl, CvType.CV_32F); Mat lum = new Mat(L.rows(), L.cols(), L.type()); for (int i = 0; i < L.rows(); i++) { for (int j = 0; j < L.cols(); j++) { double data = Math.sqrt( ( Math.pow(bCnl.get(i, j)[0] / 255.0 - L.get(i, j)[0], 2.0) + Math.pow(gCnl.get(i, j)[0] / 255.0 - L.get(i, j)[0], 2.0) + Math.pow(rCnl.get(i, j)[0] / 255.0 - L.get(i, j)[0], 2.0) ) / 3 ); lum.put(i, j, data); } } return lum; }
/** * Simplest Color Balance. Performs color balancing via histogram * normalization. * * @param img input color or gray scale image * @param percent controls the percentage of pixels to clip to white and black. (normally, choose 1~10) * @return Balanced image in CvType.CV_32F */ public static Mat SimplestColorBalance(Mat img, int percent) { if (percent <= 0) percent = 5; img.convertTo(img, CvType.CV_32F); List<Mat> channels = new ArrayList<>(); int rows = img.rows(); // number of rows of image int cols = img.cols(); // number of columns of image int chnls = img.channels(); // number of channels of image double halfPercent = percent / 200.0; if (chnls == 3) Core.split(img, channels); else channels.add(img); List<Mat> results = new ArrayList<>(); for (int i = 0; i < chnls; i++) { // find the low and high precentile values (based on the input percentile) Mat flat = new Mat(); channels.get(i).reshape(1, 1).copyTo(flat); Core.sort(flat, flat, Core.SORT_ASCENDING); double lowVal = flat.get(0, (int) Math.floor(flat.cols() * halfPercent))[0]; double topVal = flat.get(0, (int) Math.ceil(flat.cols() * (1.0 - halfPercent)))[0]; // saturate below the low percentile and above the high percentile Mat channel = channels.get(i); for (int m = 0; m < rows; m++) { for (int n = 0; n < cols; n++) { if (channel.get(m, n)[0] < lowVal) channel.put(m, n, lowVal); if (channel.get(m, n)[0] > topVal) channel.put(m, n, topVal); } } Core.normalize(channel, channel, 0.0, 255.0 / 2, Core.NORM_MINMAX); channel.convertTo(channel, CvType.CV_32F); results.add(channel); } Mat outval = new Mat(); Core.merge(results, outval); return outval; }
public static Mat enhance(Mat image, int blkSize, int patchSize, double lambda, double eps, int krnlSize) { image.convertTo(image, CvType.CV_32F); // obtain air-light double[] airlight = AirlightEstimate.estimate(image, blkSize); // obtain coarse transmission map double fTrans = 0.5; Mat T = TransmissionEstimate.transEstimate(image, patchSize, airlight, lambda, fTrans); // refine the transmission map Mat gray = new Mat(); Imgproc.cvtColor(image, gray, Imgproc.COLOR_RGB2GRAY); Core.divide(gray, new Scalar(255.0), gray); T = Filters.GuidedImageFilter(gray, T, krnlSize, eps); // dehaze List<Mat> bgr = new ArrayList<>(); Core.split(image, bgr); Mat bChannel = dehaze(bgr.get(0), T, airlight[0]); //Core.normalize(bChannel, bChannel, 0, 255, Core.NORM_MINMAX); Mat gChannel = dehaze(bgr.get(1), T, airlight[1]); //Core.normalize(gChannel, gChannel, 0, 255, Core.NORM_MINMAX); Mat rChannel = dehaze(bgr.get(2), T, airlight[2]); //Core.normalize(rChannel, rChannel, 0, 255, Core.NORM_MINMAX); Mat dehazedImg = new Mat(); Core.merge(new ArrayList<>(Arrays.asList(bChannel, gChannel, rChannel)), dehazedImg); return dehazedImg; }
public void gerarCinza(Mat original, Mat cinza) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); int width = original.width(); //largura int height = original.height(); //altura // System.out.println(width+"/"+height); for (int w = 0; w < width; w++) { for (int h = 0; h < height; h++) { // System.out.println(w+"/"+h); double[] rgb = cinza.get(h, w); double cor = ((rgb[0] + rgb[1] + rgb[2]) / 3); double[] tom = { cor, cor, cor }; cinza.put(h, w, tom); } } salvarImagem("paisagemcinza.png", cinza); }
public static Mat[] LaplacianPyramid(Mat img, int level) { Mat[] lapPyr = new Mat[level]; //Mat mask = filterMask(img); lapPyr[0] = img.clone(); Mat tmpImg = img.clone(); for (int i = 1; i < level; i++) { // resize image Imgproc.resize(tmpImg, tmpImg, new Size(), 0.5, 0.5, Imgproc.INTER_LINEAR); lapPyr[i] = tmpImg.clone(); } // calculate the DoG for (int i = 0; i < level - 1; i++) { Mat tmpPyr = new Mat(); Imgproc.resize(lapPyr[i + 1], tmpPyr, lapPyr[i].size(), 0, 0, Imgproc.INTER_LINEAR); Core.subtract(lapPyr[i], tmpPyr, lapPyr[i]); } return lapPyr; }
public void DifferenceOfGaussian() { Mat grayMat = new Mat(); Mat blur1 = new Mat(); Mat blur2 = new Mat(); //Converting the image to grayscale Imgproc.cvtColor(originalMat, grayMat, Imgproc.COLOR_BGR2GRAY); Imgproc.GaussianBlur(grayMat, blur1, new Size(15, 15), 5); Imgproc.GaussianBlur(grayMat, blur2, new Size(21, 21), 5); //Subtracting the two blurred images Mat DoG = new Mat(); Core.absdiff(blur1, blur2, DoG); //Inverse Binary Thresholding Core.multiply(DoG, new Scalar(100), DoG); Imgproc.threshold(DoG, DoG, 50, 255, Imgproc.THRESH_BINARY_INV); //Converting Mat back to Bitmap Utils.matToBitmap(DoG, currentBitmap); imageView.setImageBitmap(currentBitmap); }
public void init() { mFramesCouner = 0; mFrequency = Core.getTickFrequency(); mprevFrameTime = Core.getTickCount(); mStrfps = ""; mPaint = new Paint(); mPaint.setColor(Color.BLUE); mPaint.setTextSize(20); }
/** * 其主要思路为: 1、求取源图I的平均灰度,并记录rows和cols; 2、按照一定大小,分为N*M个方块,求出每块的平均值,得到子块的亮度矩阵D; 3、用矩阵D的每个元素减去源图的平均灰度,得到子块的亮度差值矩阵E; 4、用双立方差值法,将矩阵E差值成与源图一样大小的亮度分布矩阵R; 5、得到矫正后的图像result=I-R; * @Title: unevenLightCompensate * @Description: 光线补偿 * @param image * @param blockSize * void * @throws */ public static void unevenLightCompensate(Mat image, int blockSize) { if(image.channels() == 3) { Imgproc.cvtColor(image, image, 7); } double average = Core.mean(image).val[0]; Scalar scalar = new Scalar(average); int rowsNew = (int) Math.ceil((double)image.rows() / (double)blockSize); int colsNew = (int) Math.ceil((double)image.cols() / (double)blockSize); Mat blockImage = new Mat(); blockImage = Mat.zeros(rowsNew, colsNew, CvType.CV_32FC1); for(int i = 0; i < rowsNew; i ++) { for(int j = 0; j < colsNew; j ++) { int rowmin = i * blockSize; int rowmax = (i + 1) * blockSize; if(rowmax > image.rows()) rowmax = image.rows(); int colmin = j * blockSize; int colmax = (j +1) * blockSize; if(colmax > image.cols()) colmax = image.cols(); Range rangeRow = new Range(rowmin, rowmax); Range rangeCol = new Range(colmin, colmax); Mat imageROI = new Mat(image, rangeRow, rangeCol); double temaver = Core.mean(imageROI).val[0]; blockImage.put(i, j, temaver); } } Core.subtract(blockImage, scalar, blockImage); Mat blockImage2 = new Mat(); int INTER_CUBIC = 2; Imgproc.resize(blockImage, blockImage2, image.size(), 0, 0, INTER_CUBIC); Mat image2 = new Mat(); image.convertTo(image2, CvType.CV_32FC1); Mat dst = new Mat(); Core.subtract(image2, blockImage2, dst); dst.convertTo(image, CvType.CV_8UC1); }
/** * OpenCV only supports landscape pictures, so we gotta rotate 90 degrees. */ private Mat rotateImage(Mat image) { Mat result = emptyMat(image.rows(), image.cols(), 3); Core.transpose(image, result); Core.flip(result, result, 1); return result; }
/** * Calculate ridge frequency. */ private double ridgeFrequency(Mat ridgeSegment, Mat segmentMask, Mat ridgeOrientation, Mat frequencies, int blockSize, int windowSize, int minWaveLength, int maxWaveLength) { int rows = ridgeSegment.rows(); int cols = ridgeSegment.cols(); Mat blockSegment; Mat blockOrientation; Mat frequency; for (int y = 0; y < rows - blockSize; y += blockSize) { for (int x = 0; x < cols - blockSize; x += blockSize) { blockSegment = ridgeSegment.submat(y, y + blockSize, x, x + blockSize); blockOrientation = ridgeOrientation.submat(y, y + blockSize, x, x + blockSize); frequency = calculateFrequency(blockSegment, blockOrientation, windowSize, minWaveLength, maxWaveLength); frequency.copyTo(frequencies.rowRange(y, y + blockSize).colRange(x, x + blockSize)); } } // mask out frequencies calculated for non ridge regions Core.multiply(frequencies, segmentMask, frequencies, 1.0, CvType.CV_32FC1); // find median frequency over all the valid regions of the image. double medianFrequency = medianFrequency(frequencies); // the median frequency value used across the whole fingerprint gives a more satisfactory result Core.multiply(segmentMask, Scalar.all(medianFrequency), frequencies, 1.0, CvType.CV_32FC1); return medianFrequency; }
public static void canny(String oriImg, String dstImg, int threshold) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); final Mat img = Imgcodecs.imread(oriImg); Imgproc.cvtColor(img, img, Imgproc.COLOR_BGR2GRAY); // Imgproc.Canny(img, img, threshold, threshold * 3, 3, true); // Imgcodecs.imwrite(dstImg, img); }