今天實作將Barcode Scanner結合在我的Button上
根據昨天的AVFoundation建立出的Camera,再增加Vison套件的識別功能
讓圖像能夠作為識別
頭好痛,晚了七秒,我的鐵人賽啊
import Vision
需要要素:
流程:
透過func photoOutput去辨認detectRequest
將辨別完成的資料儲存在detectRequest
透過AfterClassfication將detectRequest裡面的資料取出,作為顯示
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
if let imageData = photo.fileDateRepresentation, let image = UIImage(data:imageData){
guard let CiImage = CIImage(image:image)else{
showAlert(withTitle:"Unable to Convert")
}
DispatchQueue.global(qos: .userInteractive).sync{
// 讓handler裝載要使用的CIImage,orientation要讓辨識知道方向是否一樣
let handler = VNImageRequestHandler(ciImage:CiImage,orientation:CGImagePropertyOrientation.up, options:[:])
do{
try handler.perform([self.detecterRequest])
}
catch{
self.showAlert(withTitle:"Error")
}
}
}
}
// 宣告一個lazy宣吿
lazy DetectRequest:VNDetectBarcodesRequest = {
return VNDetectBarcodesRequest(completionHandler:{(request,error) in
guard error = nil else{
showAlert(withTitle:"BarCode Error")
return
}
// 讓AfterDetect讀去資料
self.AfterDetect(for:request)
})
}()
// 將剛剛的DetectBarcodeRequest裡面的內容拆解出來
func AfterDetect(for request:VNRequest){
// 將物件轉型成Observation(已經辨識後的物件)
if let bestResult = request.results?.first as? VNBarcodeObservation{
if let payload = bestResult.payloadStringValue{
// 使用多執行緒的顯示UIAlertController
// 更新UI,只能使用Main thread
DispatchQueue.main.async{
let alertController = UIAlertController()
alertController.addAction(UIAlertAction(title: payload, style: .default, handler:nil))
self.present(alertController, animate: true, completion: nil)
}
}
}else{
self.showAlert(withTitle:"BarCode Error")
}
}
成果展示:
參考連結:
程式碼都是參考自
加上了一點自己DIY的理解
完整的GitHub:
heartbeat-tutorials/ViewController.swift at master · rickwierenga/heartbeat-tutorials
iOS 11 - Vision 人脸识别 - SwiftCafe 享受代码的乐趣