uniapp 安卓使用live-pusher实现人脸识别(拍照)功能

这篇具有很好参考价值的文章主要介绍了uniapp 安卓使用live-pusher实现人脸识别(拍照)功能。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1.nvue页面使用

nvue页面可以直接使用live-pusher组件。
由于live-pusher是矩形的,一般人脸识别使用圆形,所以添加cover-image可覆盖在live-pusher上层,修改样式。

<template>
	<div>
		<div class="livefater">
			<div style="width: 300px;height: 300px;border-radius: 150px;overflow: hidden;">
				<live-pusher id='livePusher' ref="livePusher" class="livePusher" url="" mode="SD" :muted="true"
					:enable-camera="true" :auto-focus="true" :beauty="1" whiteness="2" aspect="1:1"
					@statechange="statechange" @netstatus="netstatus" @error="error"></live-pusher>
			</div>
			<cover-image src="/static/faceRecognition/facebox.png" class="gaiimg"></cover-image>
		</div>
		<view class="message" style="color: #76adf1;">
			<text class="info">请平视屏幕,并正对光源,将脸部移入圆圈内</text>
		</view>
		<zero-loading v-if="loading" mask type="triangle"></zero-loading>
		<u-top-tips ref="uNotify"></u-top-tips>
	</div>
</template>

<script>
	import {
		homeMenuList,
		menuNameList
	} from '@/utils/homeListMap.js'
	import {
		getNewCount,
		getLastGroup
	} from "@/api/toChatWith.js"
	import {
		login,
		registeredUser,
		getUserInfo,
		listMenus
	} from '@/api/login.js';

	export default {
		data() {
			return {
				imgData: '',
				pusher: null,
				scanWin: null,
				faceInitTimeout: null,
				snapshTimeout: null,
				uploadFileTask: null,
				faceNum: 0,
				loading: false,
			}
		},
		mounted() {
			// 注意:需要在onReady中 或 onLoad 延时
			this.pusher = uni.createLivePusherContext("livePusher", this);
			var that = this
			setTimeout(() => {
				this.startPreview()
			})
		},
		onUnload() {
			console.log('关闭')
			this.pusher && this.pusher.close({
				success: (a) => {
					console.log("关闭");
				}
			})
		},
		methods: {
			//获取快照
			snapshotPusher() {
				var that = this
				this.pusher.snapshot({
					success: (e) => {
						console.log(e.message, '拍照信息');
						//获取图片base64
						that.getMinImage(e.message.tempImagePath);
					},
				})
			},
			// 开启摄像头
			startPreview() {
				var that = this
				this.pusher.startPreview({
					success: (a) => {
						console.log("livePusher.startPreview:" + JSON.stringify(a));
						that.snapshotPusher()
					},
					fail(err) {
						console.log(err);
					}
				});
			},
			//使用plus.zip.compressImage压缩图片
			getMinImage(imgPath) {
				plus.zip.compressImage({
						src: imgPath,
						dst: imgPath,
						overwrite: true,
						quality: 40
					},
					zipRes => {
						setTimeout(() => {
							var reader = new plus.io.FileReader();
							reader.onloadend = res => {
								//获取图片base64	
								var speech = res.target.result; //base64图片
								this.onLogin(speech)
								this.imgData = speech;
							};
							//一定要使用plus.io.convertLocalFileSystemURL将target地址转换为本地文件地址,否则readAsDataURL会找不到文件
							reader.readAsDataURL(plus.io.convertLocalFileSystemURL(zipRes.target));
						}, 100);
					},
					function(error) {
						console.log('Compress error!', error);
					}
				);
			},
			//调用登录接口
			onLogin(val) {
				login({
					"loginType": "faceLogin",
					"image": val.split(',')[1]
				}).then(async (res) => {
					console.log(res)
					if (res.code === '200' && res.data.clientUuid) { //识别成功
						//写登录逻辑
					} else { //超过五次识别未成功,则取消识别
						this.faceNum += 1
						if (this.faceNum >= 5) {
							uni.showToast({
								icon: 'none',
								title: '人员未登记!'
							})
							setTimeout(() => {
								uni.navigateBack();
							}, 2000)
						} else {
							this.snapshotPusher()
						}
					}
				}).catch(err => {
					console.log(err, '调用接口失败')
				})
			},

	
		},
	}
</script>

<style lang="less" scoped>
	/*#ifndef APP-NVUE*/
	page {
		background: #fff;
	}

	/*#endif*/

	.u-navbar__content__left {
		display: flex !important;
		align-items: center;
	}

	.u_nav_slot {
		display: flex;
		align-items: center;
		flex-direction: row;
		color: rgba(0, 0, 0, 0.9);
		font-size: 14.4rpx;
		font-weight: 700;

	}

	.text {
		margin-left: 1rpx;
		color: #fff;
		font-size: 16rpx;
	}

	.box {
		z-index: 99;
		position: absolute;
		left: 35%;
		top: 25%;
		width: 250rpx;
		height: 250rpx;
		background: pink;
	}



	.info {
		color: #76adf1 !important;
		font-size: 26rpx;
	}

	.livePusher {
		width: 300px;
		height: 300px;
	}

	.livefater {
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
		margin-top: 10rpx;
		margin-bottom: 50rpx;
		height: 350px;
		overflow: hidden;
	}

	.gaiimg {
		width: 462px;
		height: 350px;
		position: absolute;
		top: 0;
	}
</style>

2.vue页面使用

vue页面直接使用live-pusher组件将无法进入方法的回调中。
可见:官方描述
需要使用plus.video.createLivePusher方法

使用该方法,cover-image无法直接覆盖在上层,可以使用如下,添加一个html文件覆盖在上层,注意在页面销毁的时候,需要将该html隐藏! this.scanWin.hide();

  this.scanWin = plus.webview.create('/static/cover.html', '', {
                    background: 'transparent',
                    borderRaduis: '50%',
                });
                // // //新引入的webView显示
                this.scanWin.show();
<template>
    <view>
        <button style="margin-top: 500px;background-color: #3c96f3" @click="snapshotPusher">
            拍照
        </button>

        <view id="livepusher" style="width: 250px;height: 250px;background-color: #fff;margin: auto;"></view>
        <view class="tips_text">
            <text class="textphoto">正对屏幕,确保面不都在画面之内</text>
        </view>
        <zero-loading v-if="loading" mask type="triangle"></zero-loading>
        <u-top-tips ref="uNotify"></u-top-tips>
    </view>
</template>

<script>
import permission from '@/utils/permission.js'
import { homeMenuList, menuNameList } from '@/utils/homeListMap.js'
import { getNewCount, getLastGroup } from "@/api/toChatWith.js"

import { login, registeredUser, getUserInfo, listMenus } from '@/api/login.js'
export default {
    data() {
        return {
            imgData: '',
            pusher: null,
            scanWin: null,
            faceInitTimeout: null,
            snapshTimeout: null,
            uploadFileTask: null,
            intervalId: null,
            faceNum: 0,
            loading: false,
        };
    },
    methods: {
        //初始化
        faceInit() {
            this.faceInitTimeout = setTimeout(async () => {
                this.pusherInit();
                // 覆盖在视频之上的内容,根据实际情况编写
                // 利用plus.webview.create将扫描框页面及扫描动画(xxx.html)覆盖在视频之上;
                this.scanWin = plus.webview.create('/static/cover.html', '', {
                    background: 'transparent',
                    borderRaduis: '50%',
                });
                // // //新引入的webView显示
                this.scanWin.show();
            }, 1000);
        },
        //初始化播放器
        pusherInit() {
            // 获取当前窗口
            const currentWebview = this.$mp.page.$getAppWebview();
            // 创建推流,url不填写代表不上传
            this.pusher = plus.video.createLivePusher('livepusher', {
                url: '',
                top: '15%',
                left: '10%',
                width: '250px',
                height: '250px',
                position: 'absolute',
                aspect: '9:16',
                muted: false,
                'z-index': 999,
            });

            // 将推流对象加到当前页面中
            currentWebview.append(this.pusher);

            //反转摄像头
            this.pusher.switchCamera();
            //开始预览
            this.pusher.preview();

            setTimeout(() => {
                // this.snapshotPusher()
            }, 1000);
        },

        //获取快照
        snapshotPusher() {
            let that = this
            this.snapshTimeout = setTimeout(() => {
                this.pusher.snapshot(
                    e => {
                        //拿到本地文件路径
                        var src = e.tempImagePath;
                        console.log(src)
                        //获取图片base64
                        this.getMinImage(src);
                    },
                    function (e) {
                        plus.nativeUI.alert('snapshot error: ' + JSON.stringify(e));
                    }
                );
            }, 100);
        },

        //使用plus.zip.compressImage压缩图片
        getMinImage(imgPath) {
            plus.zip.compressImage({
                src: imgPath,
                dst: imgPath,
                overwrite: true,
                quality: 40
            },
                zipRes => {
                    setTimeout(() => {
                        var reader = new plus.io.FileReader();
                        reader.onloadend = res => {
                            //获取图片base64	
                            var speech = res.target.result; //base64图片
                            this.onLogin(speech)
                            this.imgData = speech;
                        };
                        //一定要使用plus.io.convertLocalFileSystemURL将target地址转换为本地文件地址,否则readAsDataURL会找不到文件
                        reader.readAsDataURL(plus.io.convertLocalFileSystemURL(zipRes.target));
                    }, 100);
                },
                function (error) {
                    console.log('Compress error!', error);
                }
            );
        },

        //调用登录接口
        onLogin(val) {
            login({
                "loginType": "faceLogin",
                "image": val.split(',')[1]
            }).then(async (res) => {
                console.log(res)
                if (res.code === '200' && res.data.clientUuid) {//识别成功
              //登录逻辑
                } else {//超过五次识别未成功,则取消识别
                    this.faceNum += 1
                    this.snapshotPusher()
                    if (this.faceNum >= 5) {
                        clearInterval(this.intervalId)
                        uni.showToast({
                            icon: 'none', title: '人员未登记!'
                        })
                        uni.navigateBack();
                    }
                }
            })
        },

        Error(message) {
            // 弹出错误提示
            this.$refs.uNotify.show({
                title: message,
                type: 'error',
                duration: '2000',
            })
        },
        handleMeus(list) {
            const menu = JSON.parse(JSON.stringify(homeMenuList))
            menuNameList.forEach(item => {
                menu[item].data = list[item] ? list[item] : []
            })
            console.log(menu, 'menu')
            this.$store.commit('SET_MENULIST', menu)
        }
    },
    onLoad(option) {
        //#ifdef APP-PLUS
        this.faceInit();
        //#endif
    },
    onUnload() {
        console.log('hide')
        this.faceInitTimeout && clearTimeout(this.faceInitTimeout);
        this.snapshTimeout && clearTimeout(this.snapshTimeout);
        this.scanWin.hide();
    },
};
</script>

<style lang="scss" scoped>
.tips_text {
    margin-top: 320px;
}
</style>

总结:更推荐使用nvue的使用方式,本人本地使用时vue方式拍照的时候会出现聚焦问题。

有朋友想要图片的可以下面自取:将水印P掉就可以了,只是简单扣了个圆,有其他需求可找自己公司的UI设计。
uniapp 安卓使用live-pusher实现人脸识别(拍照)功能,uniapp,uni-app,android,javascript,vue.js文章来源地址https://www.toymoban.com/news/detail-668074.html

到了这里,关于uniapp 安卓使用live-pusher实现人脸识别(拍照)功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 使用uniapp开发微信小程序的人脸采集功能/人脸识别功能

    ✅作者简介:大家好我是瓜子三百克,励志成为全栈工程师的一枚程序猿,也是喜欢在学习和开发中记录笔记的小白博主! 📃个人主页:瓜子三百克的主页 🔥系列专栏:uniapp前端 💖如果觉得博主的文章还不错的话,请点赞👍+收藏⭐️+留言📝支持一下博主哦🤞 本篇文章

    2024年02月11日
    浏览(41)
  • 【uniapp+云函数调用】人脸识别,实人认证,适用于app,具体思路解析,已实现

    2023.10.8 需求: uniapp开发的app项目中使用人脸识别 app项目都是第一次搞,更别提人脸识别了。目前已有的就是Dcloud账号已申请,实现需求的时间没那么紧迫 此篇会详细记录从0到1的过程 2023.10.24 今天开始探究实现的过程 可能会记录的有些冗余 效果图如下: uniapp开发指南-un

    2024年02月07日
    浏览(28)
  • Java使用opencv实现人脸识别、人脸比对

    1. opencv概述 OpenCV是一个开源的计算机视觉库,它提供了一系列丰富的图像处理和计算机视觉算法,包括图像读取、显示、滤波、特征检测、目标跟踪等功能。 opencv官网:https://opencv.org/ opencv官网文档:https://docs.opencv.org/4.7.0/index.html 参考教程1:https://www.w3cschool.cn/opencv/ 参考教

    2024年02月08日
    浏览(37)
  • vue使用tracking实现人脸识别/人脸侦测

    1、安装依赖 2、完整代码(人脸识别功能) 以下代码实现打开摄像头识别人脸 注: 1、安卓设备的人脸识别实现规则: 打开设备摄像机后,在相机的拍摄下实时进行人脸识别,如果识别到人脸后,1.5秒后自动拍照(可自行调整拍照时间)。 2、IOS设备的人脸识别实现规则:

    2024年02月15日
    浏览(24)
  • 使用opencv实现简单的人脸识别

    opencv-python是一个python绑定库,旨在解决计算机视觉问题。使用opencv模块,可以实现一些对图片和视频的操作。 安装opencv之前需要先安装numpy, matplotlib。然后使用pip安装opencv库即可。 使用import cv2进行导入即可,需要注意的是cv2读取图片的颜色通道是BGR(蓝绿红)。 使用cv2.

    2023年04月19日
    浏览(37)
  • 在Visual Studio上,使用OpenCV实现人脸识别

    本文介绍了如何在 Visual Studio 上,使用 OpenCV 来实现人脸识别的功能 环境说明 : 操作系统 : windows 10 64位 Visual Studio 版本 : Visual Studio Community 2022 (社区版) OpenCV 版本 : OpenCV-4.8.0 (2023年7月最新版) 实现效果如图所示,识别到的人脸会用红框框出来 : 这部分详见我的另一篇博客 :

    2024年02月12日
    浏览(48)
  • 使用OpenCV实现人脸特征点检测与实时表情识别

    引言:         本文介绍了如何利用 OpenCV 库实现人脸特征点检测,并进一步实现实时表情识别的案例。首先,通过 OpenCV 的Dlib库进行人脸特征点的定位,然后基于特征点的变化来识别不同的表情。这种方法不仅准确度高,而且实时性好,可以广泛应用于人脸表情分析、人

    2024年04月15日
    浏览(32)
  • uniapp调用微信小程序人脸识别步骤

    template script

    2024年02月16日
    浏览(30)
  • c#Winform使用Opencvsharp4实现简易人脸识别

         环境配置: vs2019 , .Net FrameWork 4.8  Opencvsharp4       在Nuget内下载最新的Opencvsharp4即可,        大概说一下我所理解的人脸识别的原理吧,就是先给训练器一些训练数据,就是我们告诉训练器这些数据分别对应的是哪些人,然后训练器就记住这些图像的特征以及对

    2024年02月07日
    浏览(29)
  • AIGC:初学者使用“C知道”实现AI人脸识别

    从前,我们依靠各种搜索引擎来获取内容,但随着各类数据在互联网世界的爆炸式增长,加上深度学习模型的广泛发展,我们现在不仅可以实现“遇事不决问AI”,还可以利用AI进行创作,关于人工智能生成内容(AIGC)的讨论和应用也是随处可见。 本文记录一下人工智能初学

    2024年02月11日
    浏览(38)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包