OpenCV 자바 얼굴 인식 및 재단 기능 구현

본 논문 의 사례 는 OpenCV 자바 가 사람의 얼굴 인식 과 재단 을 실현 하 는 구체 적 인 코드 를 공유 하여 여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.
설치 및 설정
1.먼저 OpenCV 를 설치한다주소.
여기 제 가 다 운 받 은 건 윈도 버 전 3.4.5 입 니 다.

그리고 설치 하면...
2.Eclipse 설정 OpenCV
Window->Preferences->Java->User Libraries

New Libraries 이름 입력

여기 제 설치 디 렉 터 리 는 D:\OpenCV 이기 때문에:

그리고 dll 을 도입 합 니 다.저 는 64 비트 기계 이기 때문에:


Ok,자바 와 OpenCV 의 얼굴 인식 을 위 한 자바 프로젝트 를 만 듭 니 다.
얼굴 인식
프로젝트 생 성 후 우선 우 클릭 하여 Properties 선택


그리고 끌 어 들 이면 됩 니 다.
haarcascade 도입frontalface_alt.xml 이 xml 파일:

나의 pom 파일 은 다음 과 같다.

 <dependencies>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 
 
 <dependency>
 <groupId>org.bytedeco.javacpp-presets</groupId>
 <artifactId>ffmpeg</artifactId>
 <version>3.1.2-1.2</version>
 </dependency>
 <dependency>
 <groupId>org.bytedeco</groupId>
 <artifactId>javacv</artifactId>
 <version>1.4.1</version>
 </dependency>
 <!-- https://mvnrepository.com/artifact/org.bytedeco.javacpp-presets/ffmpeg-platform -->
 <dependency>
 <groupId>org.bytedeco.javacpp-presets</groupId>
 <artifactId>ffmpeg-platform</artifactId>
 <version>3.4.2-1.4.1</version>
 </dependency>
 <dependency>
 <groupId>commons-io</groupId>
 <artifactId>commons-io</artifactId>
 <version>2.4</version>
 </dependency>
 
 
 <!--       -->
 <!-- https://mvnrepository.com/artifact/org.bytedeco/javacv-platform -->
 <dependency>
 <groupId>org.bytedeco</groupId>
 <artifactId>javacv-platform</artifactId>
 <version>1.4.1</version>
 </dependency>
 <!-- https://mvnrepository.com/artifact/org.bytedeco.javacpp-presets/opencv-platform -->
 <dependency>
 <groupId>org.bytedeco.javacpp-presets</groupId>
 <artifactId>opencv-platform</artifactId>
 <version>3.4.1-1.4.1</version>
 </dependency>
 
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.12</version>
 <scope>test</scope>
 </dependency>
 
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-test</artifactId>
 <scope>test</scope>
 </dependency>
 </dependencies>
내 포트 번호 수정:
server.port=8889
마지막 코드 는 다음 과 같 습 니 다.

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
 
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.io.FileUtils;
import org.opencv.core.Core;
import org.opencv.core.Mat;
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.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
 
/* 
* @author zzf 
* @date 2019 1 17    12:04:45 
*/
@RestController
public class OpenCVController {
 
 @Value("classpath:haarcascade_frontalface_alt.xml")
 private Resource xml;
 
 @PostMapping("/face")
 public void FaceDetector(HttpServletResponse response, MultipartFile file) throws IOException {
 // D:\workspace-sts-3.9.2.RELEASE\OpenCV\src\main\resources
 // String opencvpath = System.getProperty("user.dir") +
 // "\\src\\main\\resources\\";
 // String opencvDllName = opencvpath + Core.NATIVE_LIBRARY_NAME + ".dll";
 // System.load(opencvDllName);
 System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
 System.out.println("      ……");
 
 //       ,  boot             
 File targetXmlFile = new File("src/" + xml.getFilename() + "");
 FileUtils.copyInputStreamToFile(xml.getInputStream(), targetXmlFile);
 CascadeClassifier faceDetector = new CascadeClassifier(targetXmlFile.toString());
 if (faceDetector.empty()) {
 System.out.println("     ……");
 return;
 }
 //     tempFile
 File tempFile = new File("src/" + file.getOriginalFilename() + "");
 FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
 
 //        tempFile
 Mat image = Imgcodecs.imread(tempFile.toString());
 MatOfRect faceDetections = new MatOfRect();
 //       
 faceDetector.detectMultiScale(image, faceDetections);
 System.out.println(String.format("     : %s", faceDetections.toArray().length));
 Integer i = 1;
 //        image 
 for (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), 3);
 imageCut(tempFile.toString(), i+".jpg", rect.x, rect.y, rect.width, rect.height);//       
 i++;
 }
 //           
 String filename = file.getOriginalFilename();
 Imgcodecs.imwrite(filename, image);
 File imgFile = new File(filename);
 if (imgFile.exists()) {
 response.getOutputStream().write(toByteArray(imgFile));
 response.getOutputStream().close();
 }
 
 //       
 if (targetXmlFile.exists() && targetXmlFile.isFile()) {
 if (targetXmlFile.delete()) {
 System.out.println("      " + targetXmlFile + "  !");
 }
 }
 if (imgFile.exists() && imgFile.isFile()) {
 if (imgFile.delete()) {
 System.out.println("      " + imgFile + "  !");
 }
 }
 if (tempFile.exists() && tempFile.isFile()) {
 if (tempFile.delete()) {
 System.out.println("      " + tempFile + "  !");
 }
 }
 }
 
 public static void imageCut(String imagePath, String outFile, int posX, int posY, int width, int height) {
 //     
 Mat image = Imgcodecs.imread(imagePath);
 //      :  ,  X,  Y,    ,    
 Rect rect = new Rect(posX, posY, width, height);
 //       
 Mat sub = image.submat(rect); // Mat sub = new Mat(image,rect);
 Mat mat = new Mat();
 Size size = new Size(width, height);
 Imgproc.resize(sub, mat, size);//           
 Imgcodecs.imwrite(outFile, mat);
 System.out.println(String.format("      ,        : %s", outFile));
 
 }
 
 public static byte[] toByteArray(File file) throws IOException {
 File f = file;
 if (!f.exists()) {
 throw new FileNotFoundException("file not exists");
 }
 ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
 BufferedInputStream in = null;
 try {
 in = new BufferedInputStream(new FileInputStream(f));
 int buf_size = 1024;
 byte[] buffer = new byte[buf_size];
 int len = 0;
 while (-1 != (len = in.read(buffer, 0, buf_size))) {
 bos.write(buffer, 0, len);
 }
 return bos.toByteArray();
 } catch (IOException e) {
 e.printStackTrace();
 throw e;
 } finally {
 try {
 in.close();
 } catch (IOException e) {
 e.printStackTrace();
 }
 bos.close();
 }
 }
 
}
다음은 우리 남 신 들 의 사진 입 니 다.




이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기