Este artículo comparte el código específico para Java para realizar el reconocimiento facial de su referencia. El contenido específico es el siguiente
File oficial de descarga e instalación, tome Win7 como ejemplo, descargue OpenCV-2.43.3-VC14.exe
Después de la instalación, en el directorio de compilación, en el directorio de compilación, D:/opencv/build/java, obtenga OpenCV-2413.Jar, copia al directorio del proyecto, y también requiere el archivo DLL y cada archivo XML de reconocimiento para identificar diferentes características (cara, cara, ojos, etc.)
Directorio de DLL: D: /opencv/build/java/x64/opencv_java2413.dll
Directorio XML: d: /opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml (hay varios archivos de identificación en el directorio)
Estructura del proyecto:
Código específico: dado que necesita usar el archivo DLL de OpenCV, se puede colocar en la ruta de la biblioteca Java o en JRE lib. Se puede colocar en el directorio System32 en Windows, o se puede cargar dinámicamente en el código, de la siguiente manera:
Paquete OpenCV; import com.sun.scenario.effect.imagedata; importar org.opencv.core.*; importar org.opencv.core.point; importar org.opencv.highgui.highgui; importar org.opencv.imgproc.imgproc; importar org.opencv.objdetect.cascadeClassifier; import javax.imageio.imageio; import javax.swing.*; import java.awt.*; import java.awt.image.bufferedImage; import java.io.file; import java.io.ioException; importar java.util.arrays; import java.util.vector; /*** Creado por el administrador en 2017/8/17. */Public Class Test {static {// Importar una cadena de biblioteca OpenCV OPENCV Path = System.getProperty ("User.dir") + "// OpenCV // x64 //"; Cadena libpath = system.getProperty ("java.library.path"); Cadena a = opencvpath + core.native_library_name + ".dll"; System.Load (OpenCVPath + Core.native_Library_Name + ".dll"); } public static string getCutPath (string filepath) {string [] splitPath = filePath.split ("//."); return SplitPath [0]+"Cortar"+"."+SplitPath [1]; } proceso de vacío estático público (String original, Target de cadena) lanza la excepción {String originalCut = getCutPath (original); Cadena TargetCut = GetCutPath (Target); if (Detectace (original, originalcut) && detectace (target, targetCut)) {}} public static static boolean Detectace (String ImagePath, String OutFile) lanza la excepción {System.out.println ("/nrunning DetectFacedEmo"); // Cree un reconocimiento facial desde el archivo de configuración lbpcascade_frontalface.xml, que se encuentra en el directorio de instalación de OpenCV. CascadeClassifier Facedetector = new CascadeClassifier ("c: //users//administrator//desktop//opencv//haarcascade_frontalface_alt.xml"); Mat Image = HighGui.imread (ImagePath); // Detectar caras en la imagen MatoFrect FaceDetections = new MatoFrect (); Facedetector.detectMultiscale (Image, Facedetections); System.out.println (string.format ("detectado %s caras", facedetections.toarray (). Longitud)); Rect [] rects = facedetections.toarray (); if (rects! = null && rects.length> 1) {lanzar nueva runtimeException ("más de una cara"); } // dibujar una caja alrededor de cada cara reconocida rect = rects [0]; Core.rectangle (imagen, nuevo punto (rect.x-2, rect.y-2), nuevo punto (rect.x + rect.width, rect.y + rect.height), nuevo escalar (0, 255, 0)); Mat sub = Image.submat (Rect); Mat Mat = nueva mat (); Tamaño tamaño = nuevo tamaño (300, 300); Imgproc.resize (sub, mat, tamaño); // Busque la cara y guarde el retorno highgui.imwrite (outFile, MAT); // Guarde el resultado en un archivo // String filename = "c: //users//administrator//desktop//opencv//facedetection.png"; // System.out.println (string.format ("Writing %s", FileName)); // highgui.imwrite (nombre de archivo, imagen); } public static void setalpha (String ImagePath, String OutFile) { / *** Agregar elementos de prueba* Lea la imagen y dibujándola en translucente* / try {imageiCon imageiCon = new imageCon (imagePath); BufferedImage BufferedImage = new BufferedImage (imageiCon.geticonwidth (), imageiCon.geticonheight (), bufferedImage.type_4byte_abgr); Graphics2d G2D = (Graphics2D) BufferedImage.getGraphics (); g2d.drawimage (imageiCon.getImage (), 0, 0, imageiCon.getImageObServer ()); // bucle cada punto de píxel y cambie el valor alfa del punto de píxel int alfa = 100; for (int j1 = bufferedImage.getMiny (); j1 <bufferedImage.getheHight (); j1 ++) {for (int j2 = bufferedImage.getminx (); j2 <bufferedimage.getWidth (); j2 ++) {int rgb = bufferedimage.getrgb (j2, j1); rgb = ((alfa + 1) << 24) | (RGB y 0x00ffffff); BufferedImage.SetRGB (J2, J1, RGB); }} g2d.drawimage (BufferedImage, 0, 0, imageiCon.getImageObServer ()); // Generar la imagen como png imageio.write (bufferedImage, "png", nuevo archivo (outFile)); } catch (Exception e) {E.PrintStackTrace (); }} Marca de agua void estática privada (String A, String B, String Outfile, Float Alpha) lanza IOException {// Obtenga el mapa base BufferedImage buffimg = imageIO.Read (nuevo archivo (a)); // Obtener mapa de capa BufferedImage WaterImg = ImageIO.Read (nuevo archivo (b)); // Crear objeto Graphics2D y dibujar en el objeto Base Map Graphics2D G2D = Buffimg.CreateGraphics (); int waterimgwidth = waterimg.getWidth (); // get capa mapa de mapa de ancho int waterimgheight = waterimg.getheight (); // get de altura del mapa de capa // Implementar efectos de mezcla y transparentes en gráficos e imágenes g2d.setCompossite (Alphacompossite.getInstance (alphacompompresite.src_atop, AllphaS)););););););); // dibujar g2d.drawimage (waterimg, 0, 0, waterimgwidth, waterimgheight, null); g2d.dispose (); // libera los recursos del sistema utilizados en el contexto de gráficos // Generar la imagen como png imageio.write (buffimg, "png", nuevo archivo (outfile)); } public static static boolean Mergeimple (BufferedImage Image1, BufferedImage Image2, int Posw, int Posh, File FileOutput) {// fusionar dos imágenes int w1 = image1.getWidth (); int h1 = image1.getheight (); int w2 = image2.getWidth (); int h2 = image2.getheight (); BufferedImage Imagesaved = new BufferedImage (W1, H1, BufferedImage.Type_int_argb); Graphics2d G2D = ImageAved.CreateGraphics (); // Agregue el siguiente código para hacer el fondo transparente G2D.DrawImage (Image1, Null, 0, 0); image1 = g2d.getDeviceConfiguration (). CreateCompatibleImage (W1, W2, Transparencia.translucent); g2d.dispose (); g2d = image1.createGraphics (); // Fin del código transparente de fondo // para (int i = 0; i <w2; i ++) {// for (int j = 0; j <h2; j ++) {// int rgb1 = image1.getrgb (i+posw, j+posh); // int rgb2 = image2.getrgb (i, j); // if (rgb1! = rgb2) {// // rgb2 = rgb1 & rgb2; //} // Imagesaved.setRgb (i + posw, j + posh, rgb2); //} //} boolean b = false; intente {b = imageIO.Write (ImageSaved, "PNG", FileOutput); } catch (ioException IE) {ie.printStackTrace (); } retorno b; } public static void main (string [] args) lanza la excepción {String A, B, C, D; a = "c: //users//administrator//desktop//opencv//zzl.jpg"; d = "c: //users//administrator//desktop//opencv//cgx.jpg"; // proceso (a, d); a = "c: //users//administrator//desktop//opencv//zzlcut.jpg"; d = "c: //users//administrator//desktop//opencv//cgxcut.jpg"; CascadeClassifier Facedetector = new CascadeClassifier ("c: //users//administrator//desktop//opencv//haarcascade_frontalface_alt.xml"); CascadeClassifier EyEdEtector1 = nuevo cascadeClassifier ("c: //users//administrator//desktop//opencv//haarcascade_eye.xml"); CascadeClassifier EyEdEtector2 = new CascadeCLassifier ("c: //users//administrator//desktop//opencv//haarcascade_eye_tree_eyeglasses.xml"); Mat Image = HighGui.imread ("c: //users//administrator//desktop//opencv//gakki.jpg"); // detectar FaceDetections en la imagen MatoFrect Facedetections = new MatoFrect (); //EyEdetector2.DetectMultiscale(image, Facedetections); Vector <rect> objetos; EyEdetector1.DetectMultiscale (imagen, Facedetections, 2.0,1,1, nuevo tamaño (20,20), nuevo tamaño (20,20)); Rect [] rects = facedetections.toarray (); Ojo recto, ojo; ojo = rects [0]; eyeb = rects [1]; System.out.println ("A-Center Coordinate" + Eye.x + "y" + Eye.y); System.out.println ("B-Center Coordinate" + Eyeb.x + "y" + Eyeb.y); // obtener el ángulo de dos ojos dobles dy = (eyeb.y-eyea.y); doble dx = (eyeb.x-eyea.x); doble len = math.sqrt (dx*dx+dy*dy); System.out.println ("dx is"+dx); System.out.println ("dy is"+dy); System.out.println ("Len Is"+Len); ángulo doble = math.atan2 (math.abs (dy), math.abs (dx))*180.0/math.pi; System.out.println ("El ángulo es"+ángulo); for (rect rect: faceedetections.toarray ()) {core.rectangle (imagen, nuevo punto (rect.x, rect.y), nuevo punto (rect.x + rect.width, rect.y + rect.height), nuevo escalar (0, 255, 0)); } Cadena filename = "c: //users//administrator//desktop//opencv//ouput.png"; System.out.println (string.format ("Writing %s", FileName)); Highgui.imwrite (nombre de archivo, imagen); // Marca de agua (a, d, "c: //users//administrator//desktop//opencv//zzltm2.jpg", 0.7f); // // // // Lea la imagen sin cambiar la información original de la imagen // Mat Image1 = HighGui.imread (a); // Mat Image2 = HighGui.imread (D); // Mat Mat1 = nuevo mat (); Mat Mat2 = nuevo mat (); // tamaño de tamaño = nuevo tamaño (300, 300); // imgproc.resize (image1, mat1, tamaño); // imgproc.resize (imagen2, mat2, tamaño); // Mat Mat3 = nueva Mat (tamaño, cvtype.cv_64f); // Core.addweeting (MAT1, 0.5, MAT2, 1, 0, MAT3); // // // // highgui.imwrite ("c: //users//administrator//desktop//opencv//add.jpg", mat3); // // MergeSimple (ImageIO.Read (nuevo archivo (a)), // imageio.read (nuevo archivo (d)), 0,0, // nuevo archivo ("c: //users//administrator//desktop//opencv//add.jpg"); }}Efecto final: hay un borde verde al lado de la cara, y la imagen del borde verde se puede capturar para generar una imagen facial
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.