iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 28
0
Software Development

30天Swift入門學習系列 第 28

iOS App 實作(20) Face Detection


Description:
Apple 在 WWDC 2017 中發佈了 Vision 這個新的 framework,本篇來實作裡面的臉部偵測功能。


Component:

  1. UIImageView

Highlight function:
在實作 Vision framework 中物件偵測時基本上分成三個步驟,分別是:

  • Requests – 是要求 Framework 為你進行偵測。
  • Handlers – 是要 Framework 在 Request 產生後執行一些東西或處理這個 Request。
  • Observations – 是得到你想偵測之物件。

Requests 及 Handlers 實作方法如下:

let detectRequest = VNDetectFaceRectanglesRequest(completionHandler: self.handleFaces)
let detectRequestHandler = VNImageRequestHandler(cgImage: (testImg?.cgImage)!, options: [ : ])

宣告好 handler 後讓 handler 開始進行偵測的方式是呼叫該物件之 perform method。

try detectRequestHandler.perform([detectRequest])

執行完 handler 後會得到 observations 在這邊也就是人臉。

因之前已在宣告在執行完 Request 後就呼叫 handleFaces()。此 function 的功能為判斷是否有偵測到人臉,如果有就標示出人臉沒有的話就無動作。

func handleFaces(request: VNRequest, error: Error?) {
  guard let faceDetectResults = request.results as? [VNFaceObservation] else {
    fatalError("Unexpected result type from VNDetectFaceRetanglesRequest.")
  }

  if faceDetectResults.count == 0 {
    print("No face detect.")
    return
  }
    
  self.addSharpToFace(forObservations: faceDetectResults)
}

Additional:
在取得偵測結果時,每個 Observations 裡面會有 boundingBox property, 此 property 是指該偵測結果在原始圖片中的相對百分比位置,因此在繪製標示用的圖層時需額外進行座標轉換。


Reference:
Source code on Github


上一篇
iOS App 實作(19) SQLite(part 3)
下一篇
Multi-Thread handling - GCD(Grand Central Dispatch)
系列文
30天Swift入門學習30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言