您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“如何用Java實(shí)現(xiàn)人臉識(shí)別”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
1、下載demo項(xiàng)目
github地址:https://github.com/xinzhfiu/ArcSoftFaceDemo
,本地搭建數(shù)據(jù)庫(kù),創(chuàng)建表:user_face_info
。這個(gè)表主要用來(lái)存人像特征,其中主要的字段 face_feature
用二進(jìn)制類型 blob
存放人臉特征。
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for user_face_info -- ---------------------------- DROP TABLE IF EXISTS `user_face_info`; CREATE TABLE `user_face_info` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵', `group_id` int(11) DEFAULT NULL COMMENT '分組id', `face_id` varchar(31) DEFAULT NULL COMMENT '人臉唯一Id', `name` varchar(63) DEFAULT NULL COMMENT '名字', `age` int(3) DEFAULT NULL COMMENT '年紀(jì)', `email` varchar(255) DEFAULT NULL COMMENT '郵箱地址', `gender` smallint(1) DEFAULT NULL COMMENT '性別,1=男,2=女', `phone_number` varchar(11) DEFAULT NULL COMMENT '電話號(hào)碼', `face_feature` blob COMMENT '人臉特征', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時(shí)間', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時(shí)間', `fpath` varchar(255) COMMENT '照片路徑', PRIMARY KEY (`id`) USING BTREE, KEY `GROUP_ID` (`group_id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC; SET FOREIGN_KEY_CHECKS = 1;
2、修改application.properties
文件
整個(gè)項(xiàng)目還是比較完整的,只需改一些配置即可啟動(dòng),但有幾點(diǎn)注意的地方,后邊會(huì)重點(diǎn)說(shuō)明。
config.arcface-sdk.sdk-lib-path
: 存放SDK
壓縮包中的三個(gè).dll
文件的路徑
config.arcface-sdk.app-id
: 開(kāi)發(fā)者中心的APPID
config.arcface-sdk.sdk-key
:開(kāi)發(fā)者中心的SDK Key
config.arcface-sdk.sdk-lib-path=d:/arcsoft_lib config.arcface-sdk.app-id=8XMHMu71Dmb5UtAEBpPTB1E9ZPNTw2nrvQ5bXxBobUA8 config.arcface-sdk.sdk-key=BA8TLA9vVwK7G6btJh3A2FCa8ZrC6VWZLNbBBFctCz5R # druid 本地的數(shù)據(jù)庫(kù)地址 spring.datasource.druid.url=jdbc:mysql://127.0.0.1:3306/xin-master?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC spring.datasource.druid.username=junkang spring.datasource.druid.password=junkang
3、根目錄創(chuàng)建lib
文件夾
在項(xiàng)目根目錄創(chuàng)建文件夾 lib
,將下載的SDK壓縮包中的arcsoft-sdk-face-2.2.0.1.jar放入項(xiàng)目根目錄
4、引入arcsoft
依賴包
<dependency> <groupId>com.arcsoft.face</groupId> <artifactId>arcsoft-sdk-face</artifactId> <version>2.2.0.1</version> <scope>system</scope> <systemPath>${basedir}/lib/arcsoft-sdk-face-2.2.0.1.jar</systemPath> </dependency>
pom.xml
文件要配置includeSystemScope
屬性,否則可能會(huì)導(dǎo)致arcsoft-sdk-face-2.2.0.1.jar
引用不到
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <includeSystemScope>true</includeSystemScope> <fork>true</fork> </configuration> </plugin> </plugins> </build>
5、啟動(dòng)項(xiàng)目
到此為止配置完成,run
Application
文件啟動(dòng)
測(cè)試一下:http://127.0.0.1:8089/demo
,如下頁(yè)面即啟動(dòng)成功
1、錄入人臉圖像
頁(yè)面輸入名稱,點(diǎn)擊攝像頭注冊(cè)
調(diào)起本地?cái)z像頭,提交后將當(dāng)前圖像傳入后臺(tái),識(shí)別提取當(dāng)前人臉體征,保存至數(shù)據(jù)庫(kù)。
2、人臉對(duì)比
錄入完人臉圖像后測(cè)試一下能否識(shí)別成功,提交當(dāng)前的圖像,發(fā)現(xiàn)識(shí)別成功相似度92%
。但是作為程序員對(duì)什么事情都要持懷疑的態(tài)度,這結(jié)果不是老鐵在頁(yè)面寫死的吧?
為了進(jìn)一步驗(yàn)證,這回把臉擋住再試一下,發(fā)現(xiàn)提示“人臉不匹配”,證明真的有進(jìn)行比對(duì)。
簡(jiǎn)單看了一下項(xiàng)目源碼,分析一下實(shí)現(xiàn)的過(guò)程:
頁(yè)面和JS一看就是后端程序員寫的,不要問(wèn)我問(wèn)為什么?懂的自然懂,哈哈哈 ~ ,
1、JS調(diào)起本地?cái)z像頭拍照,上傳圖片文件字符串
function getMedia() { $("#mainDiv").empty(); let videoComp = " <video id='video' width='500px' height='500px' autoplay='autoplay' style='margin-top: 20px'></video><canvas id='canvas' width='500px' height='500px' style='display: none'></canvas>"; $("#mainDiv").append(videoComp); let constraints = { video: {width: 500, height: 500}, audio: true }; //獲得video攝像頭區(qū)域 let video = document.getElementById("video"); //這里介紹新的方法,返回一個(gè) Promise對(duì)象 // 這個(gè)Promise對(duì)象返回成功后的回調(diào)函數(shù)帶一個(gè) MediaStream 對(duì)象作為其參數(shù) // then()是Promise對(duì)象里的方法 // then()方法是異步執(zhí)行,當(dāng)then()前的方法執(zhí)行完后再執(zhí)行then()內(nèi)部的程序 // 避免數(shù)據(jù)沒(méi)有獲取到 let promise = navigator.mediaDevices.getUserMedia(constraints); promise.then(function (MediaStream) { video.srcObject = MediaStream; video.play(); }); // var t1 = window.setTimeout(function() { // takePhoto(); // },2000) } //拍照事件 function takePhoto() { let mainComp = $("#mainDiv"); if(mainComp.has('video').length) { let userNameInput = $("#userName").val(); if(userNameInput == "") { alert("姓名不能為空!"); return false; } //獲得Canvas對(duì)象 let video = document.getElementById("video"); let canvas = document.getElementById("canvas"); let ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0, 500, 500); var formData = new FormData(); var base64File = canvas.toDataURL(); var userName = $("#userName").val(); formData.append("file", base64File); formData.append("name", userName); formData.append("groupId", "101"); $.ajax({ type: "post", url: "/faceAdd", data: formData, contentType: false, processData: false, async: false, success: function (text) { var res = JSON.stringify(text) if (text.code == 0) { alert("注冊(cè)成功") } else { alert(text.message) } }, error: function (error) { alert(JSON.stringify(error)) } }); } else{ var formData = new FormData(); let userName = $("#userName").val(); formData.append("groupId", "101"); var file = $("#file0")[0].files[0]; var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function () { var base64 = reader.result; formData.append("file", base64); formData.append("name",userName); $.ajax({ type: "post", url: "/faceAdd", data: formData, contentType: false, processData: false, async: false, success: function (text) { var res = JSON.stringify(text) if (text.code == 0) { alert("注冊(cè)成功") } else { alert(text.message) } }, error: function (error) { alert(JSON.stringify(error)) } }); location.reload(); } } }
2、后臺(tái)解析圖片,提取人像特征
后臺(tái)解析前端傳過(guò)來(lái)的圖片,提取人像特征存入數(shù)據(jù)庫(kù),人像特征的提取主要是靠FaceEngine
引擎,順著源碼一路看下去,自己才疏學(xué)淺實(shí)在是沒(méi)懂具體是個(gè)什么樣的算法。
/* 人臉添加 */ @RequestMapping(value = "/faceAdd", method = RequestMethod.POST) @ResponseBody public Result<Object> faceAdd(@RequestParam("file") String file, @RequestParam("groupId") Integer groupId, @RequestParam("name") String name) { try { //解析圖片 byte[] decode = Base64.decode(base64Process(file)); ImageInfo imageInfo = ImageFactory.getRGBData(decode); //人臉特征獲取 byte[] bytes = faceEngineService.extractFaceFeature(imageInfo); if (bytes == null) { return Results.newFailedResult(ErrorCodeEnum.NO_FACE_DETECTED); } UserFaceInfo userFaceInfo = new UserFaceInfo(); userFaceInfo.setName(name); userFaceInfo.setGroupId(groupId); userFaceInfo.setFaceFeature(bytes); userFaceInfo.setFaceId(RandomUtil.randomString(10)); //人臉特征插入到數(shù)據(jù)庫(kù) userFaceInfoService.insertSelective(userFaceInfo); logger.info("faceAdd:" + name); return Results.newSuccessResult(""); } catch (Exception e) { logger.error("", e); } return Results.newFailedResult(ErrorCodeEnum.UNKNOWN); }
3、人像特征對(duì)比
人臉識(shí)別:將前端傳入的圖像經(jīng)過(guò)人像特征提取后,和庫(kù)中已存在的人像信息對(duì)比分析
/* 人臉識(shí)別 */ @RequestMapping(value = "/faceSearch", method = RequestMethod.POST) @ResponseBody public Result<FaceSearchResDto> faceSearch(String file, Integer groupId) throws Exception { byte[] decode = Base64.decode(base64Process(file)); BufferedImage bufImage = ImageIO.read(new ByteArrayInputStream(decode)); ImageInfo imageInfo = ImageFactory.bufferedImage2ImageInfo(bufImage); //人臉特征獲取 byte[] bytes = faceEngineService.extractFaceFeature(imageInfo); if (bytes == null) { return Results.newFailedResult(ErrorCodeEnum.NO_FACE_DETECTED); } //人臉比對(duì),獲取比對(duì)結(jié)果 List<FaceUserInfo> userFaceInfoList = faceEngineService.compareFaceFeature(bytes, groupId); if (CollectionUtil.isNotEmpty(userFaceInfoList)) { FaceUserInfo faceUserInfo = userFaceInfoList.get(0); FaceSearchResDto faceSearchResDto = new FaceSearchResDto(); BeanUtil.copyProperties(faceUserInfo, faceSearchResDto); List<ProcessInfo> processInfoList = faceEngineService.process(imageInfo); if (CollectionUtil.isNotEmpty(processInfoList)) { //人臉檢測(cè) List<FaceInfo> faceInfoList = faceEngineService.detectFaces(imageInfo); int left = faceInfoList.get(0).getRect().getLeft(); int top = faceInfoList.get(0).getRect().getTop(); int width = faceInfoList.get(0).getRect().getRight() - left; int height = faceInfoList.get(0).getRect().getBottom() - top; Graphics2D graphics2D = bufImage.createGraphics(); graphics2D.setColor(Color.RED);//紅色 BasicStroke stroke = new BasicStroke(5f); graphics2D.setStroke(stroke); graphics2D.drawRect(left, top, width, height); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(bufImage, "jpg", outputStream); byte[] bytes1 = outputStream.toByteArray(); faceSearchResDto.setImage("data:image/jpeg;base64," + Base64Utils.encodeToString(bytes1)); faceSearchResDto.setAge(processInfoList.get(0).getAge()); faceSearchResDto.setGender(processInfoList.get(0).getGender().equals(1) ? "女" : "男"); } return Results.newSuccessResult(faceSearchResDto); } return Results.newFailedResult(ErrorCodeEnum.FACE_DOES_NOT_MATCH); }
“如何用Java實(shí)現(xiàn)人臉識(shí)別”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。