Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Java to realize PC face recognition login

2025-02-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use Java to achieve PC face recognition login", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "how to use Java to achieve PC face recognition login" bar!

Realization principle

Let's take a look at the general process of implementing face recognition login. There are three main steps:

The front login page opens the camera for face recognition. Note: only identify whether there is a face in the screen.

After recognizing the face, take a photo and upload the current picture.

The backend accepts the pictures and calls the face database SDK to compare the portraits. Through it, the login is successful, and the portrait information is registered to the face database and the local mysql.

Front-end implementation

It was said above to recognize faces at the front end, so here we have to use tools, I use tracking.js, a lightweight front-end face recognition framework.

The logic of the front-end Vue code is relatively simple. After tracking.js turns on the camera to recognize the face information, it takes a picture of the video image, uploads the picture information to the background, and waits for the picture comparison result.

Data () {

Return {

ShowContainer: true, / / display

Tracker: null

TipFlag: false, / / prompt that the user has detected

Flag: false, / / determine whether the photo has been taken

Context: null, / / canvas context

RemovePhotoID: null, / / stop converting pictures

ScanTip: 'face recognition...', / / prompt text

ImgUrl:'', / / base64 format picture

Canvas: null

}

}

Mounted () {

This.playVideo ()

}

Methods: {

PlayVideo () {

Var video = document.getElementById ('video')

This.canvas = document.getElementById ('canvas')

This.context = this.canvas.getContext ('2d')

This.tracker = new tracking.ObjectTracker ('face')

This.tracker.setInitialScale (4)

This.tracker.setStepSize (2)

This.tracker.setEdgesDensity (0.1)

Tracking.track ('# video', this.tracker, {camera: true})

This.tracker.on ('track', this.handleTracked)

}

HandleTracked (event) {

This.context.clearRect (0,0, this.canvas.width, this.canvas.height)

If (event.data.length = 0) {

This.scanTip = 'face not recognized'

} else {

If (! this.tipFlag) {

This.scanTip = 'successfully identified, taking pictures, please do not move ~'

}

/ / take a picture after 1 second, only once

If (! this.flag) {

This.scanTip = 'taking pictures...'

This.flag = true

This.removePhotoID = setTimeout () = > {

This.tackPhoto ()

This.tipFlag = true

}

2000

)

}

Event.data.forEach (this.plot)

}

}

Plot (rect) {

This.context.strokeStyle ='# eb652e'

This.context.strokeRect (rect.x, rect.y, rect.width, rect.height)

This.context.font = '11px Helvetica'

This.context.fillStyle = "# fff"

This.context.fillText ('x:'+ rect.x + 'px', rect.x + rect.width + 5, rect.y + 11)

This.context.fillText ('y:'+ rect.y + 'px', rect.x + rect.width + 5, rect.y + 22)

}

/ / take a picture

TackPhoto () {

This.context.drawImage (this.$refs.refVideo, 0,0,500,500)

/ / Save to base64 format

This.imgUrl = this.saveAsPNG (this.$refs.refCanvas)

Var formData = new FormData ()

FormData.append ("file", this.imgUrl)

This.scanTip = 'logging in, please wait a moment ~'

Axios ({

Method: 'post'

Url:'/ faceDiscern'

Data: formData

}) .then (function (response) {

Alert (response.data.data)

_ window.location.href= "http://127.0.0.1:8081/home";

}) .catch (function (error) {

Console.log (error)

});

This.close ()

}

/ / Save as png,base64 format picture

SaveAsPNG (c) {

Return c.toDataURL ('image/png', 0.3)

}

/ / close and clean up resources

Close () {

This.flag = false

This.tipFlag = false

This.showContainer = false

This.tracker & & this.tracker.removeListener ('track', this.handleTracked) & & tracking.track (' # video', this.tracker, {camera: false})

This.tracker = null

This.context = null

This.scanTip =''

ClearTimeout (this.removePhotoID)

}

}

Face recognition

There has been a face recognition case before, but the way to call SDK is too cumbersome and has a large amount of code. So this time, in order to simplify the implementation, we switched to Baidu's face recognition API, which was surprisingly simple.

Don't ask me why I don't write my own face recognition tool. Don't ask, but I won't.

The API of Baidu Cloud face recognition is very friendly. The demo for all kinds of operations has been written, so you can simply correct it.

The first step is to obtain token, which is the basis of calling Baidu face recognition API.

Https://aip.baidubce.com/oauth/2.0/token?

Grant_type=client_credentials&

Client_id= [AK of Baidu Cloud App] &

Client_secret= [SK of Baidu Cloud App]

Next, we began to compare the pictures. Baidu Cloud provides an online face database. Users log in to the face database to check whether the portrait exists. If it exists, it indicates that the login is successful. If it does not exist, register to the face database. Each picture has a unique identification face_token.

Baidu face recognition API implementation is relatively simple, need to pay special attention to the parameter image_type, it has three types

BASE64: the Base64 value of the picture, the image data encoded by base64, and the size of the encoded picture is no more than 2m.

URL: the URL address of the picture (it may take too long to download the picture due to network and other reasons)

FACE_TOKEN: the unique identification of face images. When the face detection API is called, each face image is assigned a unique

FACE_TOKEN, the FACE_TOKEN detected in the same image many times is the same.

We are using an image BASE64 file here, so image_type should be set to BASE64.

@ Override

Public BaiDuFaceSearchResult faceSearch (String file) {

Try {

Byte [] decode = Base64.decode (Base64Util.base64Process (file))

String faceFile = Base64Util.encode (decode)

Map map = new HashMap ()

Map.put ("image", faceFile)

Map.put ("liveness_control", "NORMAL")

Map.put ("group_id_list", "user")

Map.put ("image_type", "BASE64")

Map.put ("quality_control", "LOW")

String param = GsonUtils.toJson (map)

String result = HttpUtil.post (faceSearchUrl, this.getAccessToken (), "application/json", param)

BaiDuFaceSearchResult searchResult = JSONObject.parseObject (result, BaiDuFaceSearchResult.class)

Log.info ("faceSearch: {}", JSON.toJSONString (searchResult))

Return searchResult

} catch (Exception e) {

Log.error ("get faceSearch error {}", e.getStackTrace ())

E.getStackTrace ()

}

Return null

}

@ Override

Public BaiDuFaceDetectResult faceDetect (String file) {

Try {

Byte [] decode = Base64.decode (Base64Util.base64Process (file))

String faceFile = Base64Util.encode (decode)

Map map = new HashMap ()

Map.put ("image", faceFile)

Map.put ("face_field", "faceshape,facetype")

Map.put ("image_type", "BASE64")

String param = GsonUtils.toJson (map)

String result = HttpUtil.post (faceDetectUrl, this.getAccessToken (), "application/json", param)

BaiDuFaceDetectResult detectResult = JSONObject.parseObject (result, BaiDuFaceDetectResult.class)

Log.info ("detectResult: {}", JSON.toJSONString (detectResult))

Return detectResult

} catch (Exception e) {

Log.error ("get faceDetect error {}", e.getStackTrace ())

E.getStackTrace ()

}

Return null

}

@ Override

Public BaiDuFaceAddResult addFace (String file, UserFaceInfo userFaceInfo) {

Try {

Byte [] decode = Base64.decode (Base64Util.base64Process (file))

String faceFile = Base64Util.encode (decode)

Map map = new HashMap ()

Map.put ("image", faceFile)

Map.put ("group_id", "user")

Map.put ("user_id", userFaceInfo.getUserId ())

Map.put ("user_info", JSON.toJSONString (userFaceInfo))

Map.put ("liveness_control", "NORMAL")

Map.put ("image_type", "BASE64")

Map.put ("quality_control", "LOW")

String param = GsonUtils.toJson (map)

String result = HttpUtil.post (addfaceUrl, this.getAccessToken (), "application/json", param)

BaiDuFaceAddResult addResult = JSONObject.parseObject (result, BaiDuFaceAddResult.class)

Log.info ("addResult: {}", JSON.toJSONString (addResult))

Return addResult

} catch (Exception e) {

Log.error ("get addFace error {}", e.getStackTrace ())

E.getStackTrace ()

}

Return null

}

Thank you for your reading, the above is the content of "how to use Java to achieve PC face recognition login". After the study of this article, I believe you have a deeper understanding of how to use Java to achieve PC face recognition login, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report