ISBN Barcode Scanner实作 Day 20

今天实作将Barcode Scanner结合在我的Button上

根据昨天的AVFoundation建立出的Camera,再增加Vison套件的识别功能

让图像能够作为识别


头好痛,晚了七秒,我的铁人赛啊


使用Vision套件

import Vision

需要要素:

1. func photoOutput (Capture完成的照片的後续处理)

2. lazy var detectRequest(辨识的要求)

3. func AfterClassfication (将辨识的东西呈现)

流程:

透过func photoOutput去辨认detectRequest

将辨别完成的资料储存在detectRequest

透过AfterClassfication将detectRequest里面的资料取出,作为显示

https://i.imgur.com/kcZ3M2s.jpg

1. func photoOutput (Capture完成的照片的後续处理)

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")
						}
			}
		}
}

2. lazy var detectRequest(辨识的要求)

// 宣告一个lazy宣吿 
lazy DetectRequest:VNDetectBarcodesRequest = {
	return VNDetectBarcodesRequest(completionHandler:{(request,error) in
		guard error = nil else{
			showAlert(withTitle:"BarCode Error")
			return
		}
		// 让AfterDetect读去资料
		self.AfterDetect(for:request)
	})
}()

3. func AfterClassfication (将辨识的东西呈现)

// 将刚刚的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 享受代码的乐趣


<<:  Day09 - this&Object Prototypes Ch3 Objects - Contents - [[Put]]

>>:  [Day 10] 从 tensorflow.keras 开始的 ResNet 生活

Unity与Photon的新手相遇旅途 | Day24-Photon房间载入设定

今天内容为房间载入的程序码设定,明天会教大家如何测试。 ...

[Java Day21] 5.1. 私有化

教材网址 https://coding104.blogspot.com/2021/06/java-5...

Day -9 while与for

while 常见用法如下: //while count = 1 while count<=5:...

[DAY-27] 假设你聆听的对象,可能知道一些你不知道的事 / 说话要精准

假设你聆听的对象,可能知道一些你不知道的事 Assume that the person you ...

[02] [Flask 快速上手笔记] 01. 建立开发环境

开发环境设定 1. 安装 python3 在 Mac 环境中预设是安装 python2 我们可以透过...