Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javaapplication1; import java.io.File; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.MatOfInt; import org.opencv.core.MatOfRect; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; import org.opencv.objdetect.CascadeClassifier; /** * * @author wra216 */ public class Ocv { private String filter; private String input; private String output; public Ocv() { //http://answers.opencv.org/question/7976/libpng-warning-image-width-is-zero-in-ihdr/ // stackoverflow. Java bug. Replace the first '/'. this.filter = getClass().getResource("lbpcascade_frontalface.xml").getPath(); if (this.filter.startsWith("/")) { this.filter = this.filter.replaceFirst("/", ""); } System.out.println(this.filter); this.input = getClass().getResource("lena.png").getPath(); if (this.input.startsWith("/")) { this.input = this.input.replaceFirst("/", ""); } System.out.println(this.input); //this.output="newLena.png"; } /** * Find faces in an image. * * @param filter Path to the xml face finding filter to use * @param input Path to the input image file * @param output Path to the output image file */ public void findFaces(String filter, String input, String output) { // load the filter and create a classifier with it File f = new File(filter); /* final CascadeClassifier faceDetector = new CascadeClassifier(f.getAbsolutePath()); */ CascadeClassifier faceDetector = new CascadeClassifier(this.filter); System.out.println("This.filter " + this.filter); // load the image and read it into a matrix File f2 = new File(input); //final Mat image = Highgui.imread(f2.getAbsolutePath()); /* final Mat image = Highgui.imread(getClass().getResource( "./AverageMaleFace.jpg").getPath()); */ Mat image = Highgui.imread(this.input); System.out.println("This.input " + this.input); // run a face detector on the image MatOfRect faceDetections = new MatOfRect(); faceDetector.detectMultiScale(image, faceDetections); // inform about faces detected, and then outline each of them System.out.println(String.format("Detected %s faces", faceDetections.toArray().length)); // Draw rectangles on the image wherever we found faces for (Rect rect : faceDetections.toArray()) { Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0)); } // save the image String filename = this.output; System.out.println(String.format("Writing %s", filename)); Highgui.imwrite(filename, image); } // cropping images public void cropEachFace(String filter, String input) { // load the filter and create a classifier with it File f = new File(filter); final CascadeClassifier faceDetector = new CascadeClassifier(this.filter); // load the image and read it into a matrix File f2 = new File(input); final Mat image = Highgui.imread(this.input); // run a face detector on the image MatOfRect faceDetections = new MatOfRect(); faceDetector.detectMultiScale(image, faceDetections); // inform about faces detected System.out.println(String.format("Detected %s faces", faceDetections.toArray().length)); // Make a separate image for each face region int i = 0; for (Rect rect : faceDetections.toArray()) { Mat cropped = new Mat(image, rect); // wow, cropping is easy! Highgui.imwrite("" + i + ".png", cropped); i++; } } // resizing images void resizeEachFace(String filter, String input) { // load the filter and create a classifier with it File f = new File(filter); final CascadeClassifier faceDetector = new CascadeClassifier(this.filter); // load the image and read it into a matrix File f2 = new File(this.input); final Mat image = Highgui.imread(f2.getAbsolutePath()); // run a face detector on the image MatOfRect faceDetections = new MatOfRect(); faceDetector.detectMultiScale(image, faceDetections); // inform about faces detected, and then outline each of them System.out.println(String.format("Detected %s faces", faceDetections.toArray().length)); int i = 0; for (Rect rect : faceDetections.toArray()) { // crop out the face Mat cropped = new Mat(image, rect); // resize the face. Mat resized = new Mat(); // change the Size to shrink or expand the image Size s = new Size(1000, 1000); Imgproc.resize(cropped, resized, s); Highgui.imwrite("" + i + ".png", resized); i++; } } public void makeFacesGray(String filter, String input, String output) { // load the filter and create a classifier with it File f = new File(filter); final CascadeClassifier faceDetector = new CascadeClassifier(this.filter); // load the image and read it into a matrix File f2 = new File(input); final Mat image = Highgui.imread(this.input); // run a face detector on the image MatOfRect faceDetections = new MatOfRect(); faceDetector.detectMultiScale(image, faceDetections); // inform about faces detected System.out.println(String.format("Detected %s faces", faceDetections.toArray().length)); // make each face gray for (Rect rect : faceDetections.toArray()) { // get a shallow copy of the submatrix for the face Mat sub = image.submat(rect); // convert it to gray, then back to BGR Imgproc.cvtColor(sub, sub, Imgproc.COLOR_BGR2GRAY, 1); Imgproc.cvtColor(sub, sub, Imgproc.COLOR_GRAY2BGR, 3); // copy back to the original image sub.copyTo(image.submat(rect)); } // save file Highgui.imwrite(this.output, image); } public void saveJPG() { MatOfInt moi = new MatOfInt(); moi.fromArray(Highgui.CV_IMWRITE_JPEG_QUALITY, 15); //Highgui.imwrite("out1.jpg", image, moi); moi.fromArray(Highgui.CV_IMWRITE_JPEG_QUALITY, 99); //Highgui.imwrite("out2.jpg", image, moi); } public void blendWithGray50(String input, String output) { // load the image and read it into a matrix File f2 = new File(input); Mat image = Highgui.imread(this.input); // clone the image, and convert it to grayscale Mat gray = image.clone(); Imgproc.cvtColor(gray, gray, Imgproc.COLOR_BGR2GRAY, 1); Imgproc.cvtColor(gray, gray, Imgproc.COLOR_GRAY2BGR, 3); // blend the two images (equal weight) into a new matrix and save it Mat dst = new Mat(); Core.addWeighted(image, .5f, gray, .5f, 0.0, dst); Highgui.imwrite(this.output, dst); } void doSobel(String input, String output) { // load the image and read it into a matrix File f2 = new File(input); Mat image = Highgui.imread(this.input); // blur the image Imgproc.GaussianBlur(image, image, new Size(3, 3), 0, 0, Imgproc.BORDER_DEFAULT); // convert the image to gray Mat gray = new Mat(); Imgproc.cvtColor(image, gray, Imgproc.COLOR_BGR2GRAY); // parameters for our conversion int scale = 1; int delta = 0; int ddepth = CvType.CV_16S; // figure out the X gradient, get its absolute value Mat gx = new Mat(); Imgproc.Sobel(gray, gx, ddepth, 1, 0, 3, scale, delta, Imgproc.BORDER_DEFAULT); Mat abs_gx = new Mat(); Core.convertScaleAbs(gx, abs_gx); // do the same for Y Mat gy = new Mat(); Imgproc.Sobel(gray, gy, ddepth, 0, 1, 3, scale, delta, Imgproc.BORDER_DEFAULT); Mat abs_gy = new Mat(); Core.convertScaleAbs(gy, abs_gy); // do a simple combine, and save it Mat grad = new Mat(); Core.addWeighted(abs_gx, 0.5, abs_gy, 0.5, 0, grad); Highgui.imwrite(this.output, grad); } void getFilePath() { try { /* Class cls = Class.forName("javaapplication1.Ocv"); // returns the ClassLoader object associated with this Class ClassLoader cLoader = cls.getClassLoader(); System.out.println(cLoader.getClass()); // finds resource with the given name URL url = cLoader.getResource("javaapplication1/lena.png"); System.out.println(this.getClass().getClassLoader().getResource("javaapplication1/lena.png")); System.out.println(ClassLoader.getSystemClassLoader().getResource("javaapplication1/lena.png")); System.out.println("Value = " + url); ClassLoader cl = getClass().getClassLoader(); URL imageURL = cl.getResource("images/lena.png"); System.out.println("Java url "+imageURL); System.out.println(System.getProperty("java.class.path"));*/ System.out.println("Lena : " + getClass().getResource("lena.png").getPath()); } catch (Exception ex) { Logger.getLogger(Ocv.class.getName()).log(Level.SEVERE, null, ex); } } void directManip(String input, String output) { // load the image and read it into a matrix File f2 = new File(input); Mat image = Highgui.imread(this.input); // we're know we're working in 24-bit color dept, so prepare a 3-byte // array for storing cells from the Matrix byte[] vec3 = new byte[3]; // Note: we are traversing every other column and every other row for (int i = 0; i < image.cols(); i += 2) { for (int j = 0; j < image.rows(); j += 2) { // get pixel, just to show how to get pixels... image.get(j, i, vec3); // create a zero pixel for (int z = 0; z < 3; ++z) vec3[z] = 0; // set the current pixel to zero image.put(j, i, vec3); } } // output the file Highgui.imwrite(this.output, image); } public String getFilter() { return filter; } public void setFilter(String filter) { this.filter = filter; } public String getInput() { return input; } public void setInput(String input) { this.input = input; } public String getOutput() { return output; } public void setOutput(String output) { this.output = output; } }