效果图:
第一种是使用camerax进行预览,android camerax预览官方文档,主要通过imageAnalysis,抓帧进行图片处理,然后通过android自带的图片人脸识别FaceDetector判断是否有人脸,有人脸保存当前抓拍的照片:
val file = File(filesDir, "head_tmp.png")
val create = Observable.create<File> { emitter ->
val intArray = IntArray(2)
iv_scan.getLocationInWindow(intArray)
val createBitmap = Bitmap.createBitmap(
bitmap, intArray[0], intArray[1], iv_scan.width, iv_scan.height
)
//必须是565才能识别
val bitmap1: Bitmap = createBitmap.copy(Bitmap.Config.RGB_565, true)
val faceDetector = FaceDetector(bitmap1.width, bitmap1.height, 1)
val array = arrayOfNulls<FaceDetector.Face>(1)
val faces = faceDetector.findFaces(bitmap1, array)
if (faces > 0) {
Log.e(TAG, "检测到脸")
val fos = FileOutputStream(file.path)
createBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
fos.flush()
fos.close()
emitter.onNext(file)
} else {
Log.e(TAG, "未检测到脸")
emitter.onError(Throwable("未检测到脸"))
}
}
var disposable: Disposable? = null
val observer = object : Observer<File> {
override fun onNext(t: File) {
disposable?.dispose()
isOne = false
setResult(Activity.RESULT_OK)
finish()
}
override fun onError(e: Throwable) {
isOne = true
}
override fun onComplete() {
}
override fun onSubscribe(d: Disposable) {
disposable = d
}
}
create.subscribeOn(Schedulers.computation())//指定被观察者线程
.observeOn(AndroidSchedulers.mainThread())//指定观察者线程
.subscribe(observer)
第二种使用了免费的虹软识别人脸识别,主要判断指定识别框的rect和虹软人脸识别框的rect,比较两个rect,是否在它的范围内,如果在抓拍人脸:
if (drawInfoList.size > 0) {
for (i in drawInfoList.indices) {
val rect: Rect = drawInfoList[i].rect
val rect1 = Rect()
iv_scan.getGlobalVisibleRect(rect1)
if (rect1.contains(rect)) {
//为了美观,扩大rect截取注册图
val cropRect: Rect =
CommUtils.getBestRect(
previewSize!!.width, previewSize!!.height, faceInfoList[i].rect
)
cropRect.left = cropRect.left and 3.inv()
cropRect.top = cropRect.top and 3.inv()
cropRect.right = cropRect.right and 3.inv()
cropRect.bottom = cropRect.bottom and 3.inv()
headBmp = CommUtils.getHeadImage(
nv21,
previewSize!!.width,
previewSize!!.height,
faceInfoList[i].orient,
cropRect,
ArcSoftImageFormat.NV21
)
headBmp?.apply {
cropBitmap(this)
}
break
}
}
}
demo:https://github.com/withyi9223/facesb