이 기사는 Java가 참조에 대한 얼굴 인식을 실현할 수있는 특정 코드를 공유합니다. 특정 내용은 다음과 같습니다
공식 다운로드 및 설치 파일, Win7을 예로 들어 OpenCV-2.4.13.3-vc14.exe 다운로드하십시오.
설치 후 빌드 디렉토리에서 빌드 디렉토리 D :/opencv/build/java에서 opencv-2413.jar를 얻고 프로젝트 디렉토리에 복사하고 DLL 파일과 각각의 인식 XML 파일 (얼굴, 측면, 눈 등)을 식별해야합니다.
dll 디렉토리 : d : /opencv/build/java/x64/opencv_java2413.dll
XML 디렉토리 : d : /opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml (디렉토리에 다양한 식별 파일이 있습니다)
프로젝트 구조 :
특정 코드 : OpenCV의 DLL 파일을 사용해야하므로 Java 라이브러리 경로 또는 JRE Lib에 배치 할 수 있습니다. Windows의 System32 디렉토리에 배치하거나 코드에 동적으로로드 할 수 있습니다.
패키지 opencv; com.sun.scenario.effect.imagedata import; import org.opencv.core.*; import org.opencv.core.point; import org.opencv.highgui.highgui; import org.opencv.imgproc.imgproc; import org.opencv.objdetect.cascadeclassifier; import javax.imageio.imageio; javax.swing을 가져옵니다.*; java.awt.*; java.awt.image.bufferedimage import; import java.io.file; import java.io.ioexception; import java.util.arrays; import java.util.vector; /*** 2017/8/17의 관리자가 작성했습니다. */public class test {static {// opencv library string opencv path = system.getProperty ( "user.dir") + "// opencv // x64 //"; 문자열 libpath = system.getProperty ( "java.library.path"); 문자열 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]+"컷"+"."+SplitPath [1]; } public static void process (String Original, String Target)는 예외 {string originalcut = getCutPath (Original); 문자열 targetcut = getCutPath (대상); if (detectface (Original, OriginalCut) && detectface (target, targetcut)) {}} public static boolean detectface (String imagePath, String Outfile)는 예외 {system.out.println ( "/nrunning detectFacedEmo"); // OpenCV 설치 디렉토리에 위치한 구성 파일 LBPCASCADE_FRONTALFACE.XML에서 얼굴 인식기를 만듭니다. cascadeclassifier facedetector = 새로운 cascadeclassifier ( "c : //users//administrator//desktop//opencv//haarcascade_frontalface_alt.xml"); mat image = highgui.imread (ImagePath); // 그림의 얼굴 감지 matofrect facedetection = new matofrect (); facedetector.detectmultiscale (이미지, facedetections); System.out.println (String.format ( "감지 %s면", facedetections.toarray (). length)); rect [] rects = facedetections.toArray (); if (rects! = null && rects.length> 1) {새로운 runtimeexception ( "두 개 이상의 얼굴"); } // 각 인식 된면 주위에 상자를 그립니다. core.rectangle (이미지, 새 포인트 (rect.x-2, rect.y-2), New Point (rect.x + rect.width, rect.y + rect.height), 새 스칼라 (0, 255, 0)); mat sub = image.submat (rect); MAT MAT = 새로운 MAT (); 크기 크기 = 새 크기 (300, 300); imgproc.resize (sub, mat, size); // 얼굴을 검색하고 리턴 HighGui.imwrite (Outfile, mat)를 저장합니다. // 결과를 파일에 저장 // string filename = "c : //users//administrator//desktop//opencv//facedetection.png"; // system.out.println (String.format ( "쓰기 %s", filename)); // highgui.imwrite (filename, image); } public static void setalpha (String imagePath, String Outfile) { / *** 테스트 항목 추가* 이미지를 읽고 반투명으로 그립니다.* / try {imageicon imageicon = new ImageIcon (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 ()); // 모든 픽셀 포인트를 루프하고 픽셀 포인트 int alpha = 100의 알파 값을 변경합니다. for (int j1 = bufferedImage.getMiny (); rgb = ((alpha + 1) << 24) | (RGB & 0X00FFFFFF); BufferedImage.setrgb (j2, j1, rgb); }} g2d.DrawImage (bufferedImage, 0, 0, imageIcon.getImageObserver ()); // 이미지를 png imageio.write로 생성합니다 (bufferedImage, "png", new File (Outfile)); } catch (예외 e) {e.printstacktrace (); }} private static void watermark (문자열 a, 문자열 b, String atfile, float alpha) ioexception 던지기 {// 기본 맵 bufferedImage buffimg = imageio.Read (새 파일 (a)); // 레이어 맵 가져 오기 bufferedImage waterimg = imageio.Read (새 파일 (b)); // 그래픽 2D 객체를 만들고 기본 맵 객체 graphics2d g2d = buffimg.creategraphics ()를 그립니다. int waterimgwidth = waterimg.getwidth (); // 레이어 맵 vatth w watemgheight = waterimg.getheight (); // 레이어 맵 높이 // 그래픽 및 이미지에서 믹싱 및 투명 효과 구현 G2D.SetComposite (alphacomposite.getInstance, alpha)); // G2D.DrawImage (WaterImg, 0, 0, WaterImgWidth, WaterImgheight, NULL); g2d.dispose (); // 그래픽 컨텍스트에 사용 된 시스템 리소스를 릴리스 // 이미지를 png imageio.write로 생성합니다 (buffimg, "png", new File (Outfile)); } public static boolean mergesimple (bufferedImage image1, bufferedImage image2, int posw, int posh, file filesput) {// 두 이미지 병합 int w1 = image1.getWidth (); int h1 = image1.getheight (); int w2 = image2.getWidth (); int h2 = image2.getheight (); bufferedImage imagesAved = 새로운 bufferedImage (w1, h1, bufferedImage.type_int_argb); Graphics2d G2D = imagesAved.CreateGraphics (); // 배경을 투명하게 만들기 위해 다음 코드를 추가합니다. G2D.DrawImage (image1, null, 0, 0); image1 = g2d.getDeviceConfiguration (). CreateCompatibleImage (W1, W2, Transparency.Translucent); g2d.dispose (); g2d = image1.creategraphics (); // 배경 끝 투명 코드 // for (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); //} //} 부울 b = 거짓; try {b = imageio.write (imagesAved, "png", fileoutput); } catch (ioException IE) {ie.printstacktrace (); } 반환 b; } public static void main (String [] args)은 예외 {문자열 a, b, c, d; a = "c : //users//administrator//desktop//opencv//zzl.jpg"; d = "c : //users//administrator//desktop//opencv//cgx.jpg"; // 프로세스 (a, d); a = "c : //users//administrator//desktop//opencv//zzlcut.jpg"; d = "c : //users//administrator//desktop//opencv//cgxcut.jpg"; cascadeclassifier facedetector = 새로운 cascadeclassifier ( "c : //users//administrator//desktop//opencv//haarcascade_frontalface_alt.xml"); cascadeclassifier eyedetector1 = 새로운 cascadeclassifier ( "c : //users//administrator//desktop//opencv//haarcascade_eye.xml"); cascadeclassifier eyedetector2 = 새로운 cascadeclassifier ( "c : //users//administrator//desktop//opencv//haarcascade_eye_tree_eyeglasses.xml"); mat image = highgui.imread ( "c : //users//administrator//desktop//opencv//gakki.jpg"); // 그림에서 facedetections 감지 matofrect facedetection = new matofrect (); //eyedetector2.detectmultiscale(image, facedetections); 벡터 <rect> 객체; eyedetector1.DetectMultiscale (이미지, 대면, 2.0,1,1, 새 크기 (20,20), 새 크기 (20,20)); rect [] rects = facedetections.toArray (); 직접 눈, 눈; 눈 = rects [0]; Eyeb = rects [1]; System.out.println ( "A- 센터 좌표" + Eye.x + "및" + Eye.y); System.out.println ( "B- 센터 좌표" + Eyeb.x + "및" + Eyeb.y); // 두 눈의 각도를 얻습니다. Double dy = (Eyeb.y-eyea.y); Double DX = (Eyeb.x-eyea.x); Double Len = Math.sqrt (dx*dx+dy*dy); System.out.println ( "dx는"+dx); System.out.println ( "dy is"+dy); System.out.println ( "Len은"+Len); 이중 각도 = math.atan2 (math.abs (dy), math.abs (dx))*180.0/math.pi; System.out.println ( "각도"+각도); for (rect rect : facedetections.toarray ()) {core.rectangle (이미지, 새 포인트 (rect.x, rect.y), new Point (rect.x + rect.width, rect.y + rect.height), new Scalar (0, 255, 0)); } string filename = "c : //users//administrator//desktop//opencv//ouput.png"; System.out.println (String.format ( "쓰기 %s", filename)); highgui.imwrite (filename, image); // WaterMark (a, d, "c : //users//administrator//desktop//opencv//zzltm2.jpg", 0.7f); // // // // 이미지의 원본 정보를 변경하지 않고 이미지를 읽습니다. // mat image1 = highgui.imread (a); // mat image2 = highgui.imread (d); // MAT MAT1 = 새로운 MAT (); MAT MAT2 = 새로운 MAT (); // 크기 크기 = 새 크기 (300, 300); // imgproc.resize (image1, mat1, size); // imgproc.resize (image2, mat2, size); // MAT MAT3 = 새로운 매트 (크기, cvtype.cv_64f); // core.addweighted (MAT1, 0.5, MAT2, 1, 0, MAT3); // // // highgui.imwrite ( "c : //users//administrator//desktop//opencv//add.jpg", mat3); // // mergesimple (imageio.read (새 파일 (a)), // imageio.read (new file (d)), 0,0, // new File ( "c : //users//administrator//desktop//opencv//add.jpg"); }}최종 효과 : 얼굴 옆에 녹색 경계가 있으며 녹색 테두리 이미지를 캡처하여 얼굴 이미지를 생성 할 수 있습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.