利用 iOS 14 Vision 的手势估测功能 实作无接触即可滑动的 Tinder App
vision 框架在 2017 年推出,目的是为了让行动 app 开发者轻松利用电脑视觉演算法。具体来说,vision 框架中包含了许多预先训练好的深度学习模型,同时也能充当包裹器 (wrapper) 来快速执行你客制化的 core ml 模型。
apple 在 ios 13 推出了文字辨识 (text recognition) 和 visionkit 来增强 ocr 之后,现在将重点转向了 ios 14 vision 框架中的运动与动作分类上。
在之前的文章中,我们说过 vision 框架可以做轮廓侦测 (contour detection)、光流请求 (optical flow request),并提供一系列离线影片处理 (offline video processing) 的工具。不过更重要的是,我们现在可以进行手部与身体姿势估测 (hand and body pose estimation) ,这无疑为扩增实境 (augmented reality) 与电脑视觉带来了更多可能性。
在这篇文章中,我们会以手势估测功能来建构一个 ios app,在无接触 (touchless) 的情况下 ,app 也能够感应手势。
我之前已经发表过,展示如何使用 ml kit 的脸部侦测 api,来建构无接触滑动的 ios app。我觉得这个雏型 (prototype) 非常好用,可以整合到像是 tinder 或 bumble 等这种约会 app 中。不过,这种方式可能会因为持续眨眼和转动头部,而造成眼睛疲劳或头痛。
因此,我们简单地扩展这个范例,透过手势代替触摸,来往左或往右滑动。毕竟近年来说,使用手机来生活得更懒惰、或是练习社交距离也是合理的。在我们深入研究之前,先来看看如何在 ios 14 中创建一个视觉手势请求。
视觉手势估测
这个新的 vndetecthumanhandposerequest
,是一个基于影像的视觉请求,用来侦测一个人的手势。在型别为 vnhumanhandposeobservation
的实例当中,这个请求会在每隻手上回传 21 个标记点 (landmark point)。我们可以设定 maximumhandcount
数值,来控制在视觉处理过程之中,每张帧最多可以侦测的数量。
我们可以简单地在实例中如此使用列举 (enum),来获得每隻手指的标记点阵列 (array):
try observation.recognizedpoints(.thumb) try observation.recognizedpoints(.indexfinger) try observation.recognizedpoints(.middlefinger) try observation.recognizedpoints(.ringfinger) try observation.recognizedpoints(.littlefinger)
这裡也有一个手腕的标记点,位置就在手腕的中心点位置。它并不属于上述的任何群组,而是在 all
群组之中。你可以透过下列方式获得它:
let wristpoints = try observation.recognizedpoints(.all)
我们拿到上述的标记点阵列后,就可以这样将每个点独立抽取出来:
guard let thumbtippoint = thumbpoints[.thumbtip], let indextippoint = indexfingerpoints[.indextip], let middletippoint = middlefingerpoints[.middletip], let ringtippoint = ringfingerpoints[.ringtip], let littletippoint = littlefingerpoints[.littletip], let wristpoint = wristpoints[.wrist]else {return}
thumbip
、thumbmp
、thumbcmc
是可以在 thumb 群组中获取的其他标记点,这也适用于其他手指。
每个独立的标记点物件,都包含了它们在 avfoundation
座标系统中的位置及 confidence
阀值 (threshold)。
接著,我们可以在点跟点之间找到距离或角度的资讯,来创建手势处理器。举例来说,在 apple 的范例 app 中,他们计算拇指与食指指尖的距离,来创建一个捏 (pinch) 的手势。
开始动工
现在我们已经了解视觉手势请求的基础知识,可以开始深入研究如何实作了!
开启 xcode 并创建一个新的 uikit app,请确认你有将开发目标设定为 ios 14,并在 info.plist
设置 nscamerausagedescription
字串。
我在介绍过如何建立一个带有动画的 tinder 样式卡片,现在可以直接参考当时的。
同样地,你可以在参考 stackcontainerview.swift 类别的程式码,这个类别是用来储存多个 tinder 卡片的。
利用 avfoundation 设置相机
接下来,让我们利用 apple 的 avfoundation
框架来建立一个客制化相机。
以下是 viewcontroller.swift
档案的程式码:
class viewcontroller: uiviewcontroller, handswiperdelegate{ //mark: - properties var modeldata = [datamodel(bgcolor: .systemyellow), datamodel(bgcolor: .systemblue), datamodel(bgcolor: .systemred), datamodel(bgcolor: .systemteal), datamodel(bgcolor: .systemorange), datamodel(bgcolor: .brown)] var stackcontainer : stackcontainerview! var buttonstackview: uistackview! var leftbutton : uibutton!, rightbutton : uibutton! var cameraview : cameraview! //mark: - init override func loadview() { view = uiview() stackcontainer = stackcontainerview() view.addsubview(stackcontainer) configurestackcontainer() stackcontainer.translatesautoresizingmaskintoconstraints = false addbuttons() configurenavigationbarbuttonitem() addcameraview() } override func viewdidload() { super.viewdidload() title = "handposeswipe" stackcontainer.datasource = self } private let videodataoutputqueue = dispatchqueue(label: "camerafeeddataoutput", qos: .userinteractive) private var camerafeedsession: avcapturesession? private var handposerequest = vndetecthumanhandposerequest() let message = uilabel() var handdelegate : handswiperdelegate? func addcameraview() { cameraview = cameraview() self.handdelegate = self view.addsubview(cameraview) cameraview.translatesautoresizingmaskintoconstraints = false cameraview.bottomanchor.constraint(equalto: view.bottomanchor).isactive = true cameraview.centerxanchor.constraint(equalto: view.centerxanchor).isactive = true cameraview.widthanchor.constraint(equaltoconstant: 150).isactive = true cameraview.heightanchor.constraint(equaltoconstant: 150).isactive = true } //mark: - configurations func configurestackcontainer() { stackcontainer.centerxanchor.constraint(equalto: view.centerxanchor).isactive = true stackcontainer.centeryanchor.constraint(equalto: view.centeryanchor, constant: -60).isactive = true stackcontainer.widthanchor.constraint(equaltoconstant: 300).isactive = true stackcontainer.heightanchor.constraint(equaltoconstant: 400).isactive = true } func addbuttons() { //full source of ui setup at the end of this article } @objc func onbuttonpress(sender: uibutton){ uiview.animate(withduration: 2.0, delay: 0, usingspringwithdamping: cgfloat(0.20), initialspringvelocity: cgfloat(6.0), options: uiview.animationoptions.allowuserinteraction, animations: { sender.transform = cgaffinetransform.identity }, completion: { void in() }) if let firstview = stackcontainer.subviews.last as? tindercardview{ if sender.tag == 0{ firstview.leftswipeclicked(stackcontainerview: stackcontainer) } else{ firstview.rightswipeclicked(stackcontainerview: stackcontainer) } } } func configurenavigationbarbuttonitem() { navigationitem.rightbarbuttonitem = uibarbuttonitem(title: "reset", style: .plain, target: self, action: #selector(resettapped)) } @objc func resettapped() { stackcontainer.reloaddata() } override func viewdidappear(_ animated: bool) { super.viewdidappear(animated) do { if camerafeedsession == nil { cameraview.previewlayer.videogravity = .resizeaspectfill try setupavsession() cameraview.previewlayer.session = camerafeedsession } camerafeedsession?.startrunning() } catch { apperror.display(error, inviewcontroller: self) } } override func viewwilldisappear(_ animated: bool) { camerafeedsession?.stoprunning() super.viewwilldisappear(animated) } func setupavsession() throws { // select a front facing camera, make an input. guard let videodevice = avcapturedevice.default(.builtinwideanglecamera, for: .video, position: .front) else { throw apperror.capturesessionsetup(reason: "could not find a front facing camera.") } guard let deviceinput = try? avcapturedeviceinput(device: videodevice) else { throw apperror.capturesessionsetup(reason: "could not create video device input.") } let session = avcapturesession() session.beginconfiguration() session.sessionpreset = avcapturesession.preset.high // add a video input. guard session.canaddinput(deviceinput) else { throw apperror.capturesessionsetup(reason: "could not add video device input to the session") } session.addinput(deviceinput) let dataoutput = avcapturevideodataoutput() if session.canaddoutput(dataoutput) { session.addoutput(dataoutput) // add a video data output. dataoutput.alwaysdiscardslatevideoframes = true dataoutput.videosettings = [kcvpixelbufferpixelformattypekey as string: int(kcvpixelformattype_420ypcbcr8biplanarfullrange)] dataoutput.setsamplebufferdelegate(self, queue: videodataoutputqueue) } else { throw apperror.capturesessionsetup(reason: "could not add video data output to the session") } session.commitconfiguration() camerafeedsession = session } }
在上面的程式码中包含了许多步骤,让我们一一来分析:
-
cameraview
是一个客制化的 uiview 类别,用来在画面上呈现相机的内容。之后我们会进一步讲解这个类别。 - 我们会在
setupavsession()
设置前置相机镜头,并将它设置为avcapturesession
的输入。 - 接著,我们在
avcapturevideodataoutput
上呼叫setsamplebufferdelegate
。
而 viewcontroller
类别要遵循 handswiperdelegate
协定:
protocol handswiperdelegate { func thumbsdown() func thumbsup() }
当侦测到手势后,我们将会触发相对应的方法。现在,让我们来看看要如何在捕捉到的影像中执行视觉请求。
在捕捉到的影像中执行视觉手势请求
在以下程式码中,我们为上述的 viewcontroller
创建了一个扩展 (extension),而这个扩展遵循 avcapturevideodataoutputsamplebufferdelegate
协定:
extension viewcontroller: avcapturevideodataoutputsamplebufferdelegate { public func captureoutput(_ output: avcaptureoutput, didoutput samplebuffer: cmsamplebuffer, from connection: avcaptureconnection) { var thumbtip: cgpoint? var wrist: cgpoint? let handler = vnimagerequesthandler(cmsamplebuffer: samplebuffer, orientation: .up, options: [:]) do { // perform vndetecthumanhandposerequest try handler.perform([handposerequest]) guard let observation = handposerequest.results?.first else { cameraview.showpoints([]) return } // get points for all fingers let thumbpoints = try observation.recognizedpoints(.thumb) let wristpoints = try observation.recognizedpoints(.all) let indexfingerpoints = try observation.recognizedpoints(.indexfinger) let middlefingerpoints = try observation.recognizedpoints(.middlefinger) let ringfingerpoints = try observation.recognizedpoints(.ringfinger) let littlefingerpoints = try observation.recognizedpoints(.littlefinger) // extract individual points from point groups. guard let thumbtippoint = thumbpoints[.thumbtip], let indextippoint = indexfingerpoints[.indextip], let middletippoint = middlefingerpoints[.middletip], let ringtippoint = ringfingerpoints[.ringtip], let littletippoint = littlefingerpoints[.littletip], let wristpoint = wristpoints[.wrist] else { cameraview.showpoints([]) return } let confidencethreshold: float = 0.3 guard thumbtippoint.confidence > confidencethreshold && indextippoint.confidence > confidencethreshold && middletippoint.confidence > confidencethreshold && ringtippoint.confidence > confidencethreshold && littletippoint.confidence > confidencethreshold && wristpoint.confidence > confidencethreshold else { cameraview.showpoints([]) return } // convert points from vision coordinates to avfoundation coordinates. thumbtip = cgpoint(x: thumbtippoint.location.x, y: 1 - thumbtippoint.location.y) wrist = cgpoint(x: wristpoint.location.x, y: 1 - wristpoint.location.y) dispatchqueue.main.async { self.processpoints([thumbtip, wrist]) } } catch { camerafeedsession?.stoprunning() let error = apperror.visionerror(error: error) dispatchqueue.main.async { error.displayinviewcontroller(self) } } } }
值得注意的是,vnobservation
所回传的标记点是属于 vision 座标系统的。我们必须将它们转换成 uikit 座标,才能将它们绘制在萤幕上。
因此,我们透过以下方式将它们转换为 avfoundation 座标:
wrist = cgpoint(x: wristpoint.location.x, y: 1 - wristpoint.location.y)
接著,我们将会把这些标记点传递给 processpoints
函式。为了精简流程,这裡我们只用了拇指指尖与手腕两个标记点来侦测手势。
以下是 processpoints
函式的程式码:
func processpoints(_ points: [cgpoint?]) { let previewlayer = cameraview.previewlayer var pointsconverted: [cgpoint] = [] for point in points { pointsconverted.append(previewlayer.layerpointconverted(fromcapturedevicepoint: point!)) } let thumbtip = pointsconverted[0] let wrist = pointsconverted[pointsconverted.count - 1] let ydistance = thumbtip.y - wrist.y if(ydistance > 50){ if self.restinghand{ self.restinghand = false self.handdelegate?.thumbsdown() } }else if(ydistance < -50){ if self.restinghand{ self.restinghand = false self.handdelegate?.thumbsup() } } else{ self.restinghand = true } cameraview.showpoints(pointsconverted) }
我们可以利用以下这行程式码,将 avfoundation 座标转换为 uikit 座标:
previewlayer.layerpointconverted(fromcapturedevicepoint: point!)
最后,我们会依据两个标记点之间的绝对阈值距离,触发对推叠卡片往左或往右滑动的动作。
我们利用 cameraview.showpoints(pointsconverted)
,在 cameraview
子图层上绘制一条连接两个标记点的直线。
以下是 cameraview
类别的完整程式码:
import uikit import avfoundation class cameraview: uiview { private var overlaythumblayer = cashapelayer() var previewlayer: avcapturevideopreviewlayer { return layer as! avcapturevideopreviewlayer } override class var layerclass: anyclass { return avcapturevideopreviewlayer.self } override init(frame: cgrect) { super.init(frame: frame) setupoverlay() } required init?(coder: nscoder) { super.init(coder: coder) setupoverlay() } override func layoutsublayers(of layer: calayer) { super.layoutsublayers(of: layer) if layer == previewlayer { overlaythumblayer.frame = layer.bounds } } private func setupoverlay() { previewlayer.addsublayer(overlaythumblayer) } func showpoints(_ points: [cgpoint]) { guard let wrist: cgpoint = points.last else { // clear all calayers clearlayers() return } let thumbcolor = uicolor.green drawfinger(overlaythumblayer, array(points[0...1]), thumbcolor, wrist) } func drawfinger(_ layer: cashapelayer, _ points: [cgpoint], _ color: uicolor, _ wrist: cgpoint) { let fingerpath = uibezierpath() for point in points { fingerpath.move(to: point) fingerpath.addarc(withcenter: point, radius: 5, startangle: 0, endangle: 2 * .pi, clockwise: true) } fingerpath.move(to: points[0]) fingerpath.addline(to: points[points.count - 1]) layer.fillcolor = color.cgcolor layer.strokecolor = color.cgcolor layer.linewidth = 5.0 layer.linecap = .round catransaction.begin() catransaction.setdisableactions(true) layer.path = fingerpath.cgpath catransaction.commit() } func clearlayers() { let emptypath = uibezierpath() catransaction.begin() catransaction.setdisableactions(true) overlaythumblayer.path = emptypath.cgpath catransaction.commit() } }
最终成果
最终 app 的成果会是这样:
结论
我们可以在许多情况下用到 vision 新的手势估测请求,包括利用手势来进行自拍、绘制签名,甚至是辨识川普在演讲当中不同的手势。
你也可以将视觉请求与身体姿势请求串接在一起,用来建构更複杂的姿态。
你可以在 github 储存库 参考这个专案的完整程式码。
这篇文章到此为止,感谢你的阅读!
文末推荐:ios热门文集
上一篇: SwiftUI 简明教程之自定义对齐方式
下一篇: 逆向工程三之工具篇