CoreML

Updated:

머신러닝 학습기능은 macOS에만 포함되어 있다.

import CreateMLUI

MLImageClassifierBuilder().showInLiveView()
//실행시키면 머신러닝이 실행될 준비가 되었다.
// training시킬 이미지를 집어넣으면 된다.
// 그다음 testing 이미지를 집어넣고 테스트를 해준다.

학습자체가 되게 쉬워졌다. playground로 모델 먼저 생성을 해준다. 머신러닝 모델 파일은 프로젝트 안에다 집어넣어준다. 굉장히 가볍기 때문에 학습을 많이 시켜도 용량 걱정은 안해줘도 된다.

  • 사진을 가져오는
import vision

var picker = UIImagePickerController()

override func viewDidLoad(){
	super.viewDidLoad()
	picker.delegate = self
	func processImage(_ image: UIImage){
		//머신러닝에서 필요한 코드들 작성.
		//ML Model
		if let model = try? VNCoreMLModel(for: MLModel){//만든 모델의 파일이름을 가져와서 인스턴스화 시키면 된다.
					   //ex) DinoClassifier().model

				let request = VNCoreMLRequest(model: model) {(request, error) in
					if let results = request.results as? [VNClassificationObservation]{
					//머신러닝 모델을 폴더를 세개를 이용해서 세가지 타입을 만들었다하면, 
					//세가지의 결과값을 다 보여준다.
					//anytype이므로 캐스팅을 해준다.
					let firstValue = results.sorted(by: { (lh, rh) -> Bool in
						//lh.identifier
						//폴더이름
						//lh.confidence
						//매칭률.
						return lh.confidence > rh.confidence

					}).first

					if let bestMatch = firstValue{
						self.nameLabel.text = bestMatch.identifier
						self.percentLabel.text = "\(bestMatch.confidence * 100)%"

					}
				}	
		}
			//image data
			if let imageData = image.jpegData(compressionQuality: 0.7){
				//해상도를 약간 낮춰서 가져온다.
				let handler = VNImageRequestHandler(data: imageData, options: [:])
				try? handler.perform([request])
			}
		}else{
		}
	}
}	


extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
	func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){
		//이미지를 선택했을 때, 선택한 이미지에 대한 처리를 할 수 있다.
		if let image = info[.originalImage] as? UIImage{
			self.dinoImageView.image = image
			self.processImage(image)
		}
		//info는 anytype이여서 UIImage 형태로 가져올 수 있는지 확인하는 과정.


		picker.dismiss(animated: true, completion: nil)
	}
}

@IBAction func showCamera(_ sender: Any){
	picker.sourceType = .camera
	self.present(picker, animated: true, completion: nil)

}
@IBAction func openPhotoLibrary(_ sender: Any){
	picker.sourceType = .photoLibrary
	self.present(picker, animated: true, completion: nil
}

info.plist에가서 Privacy - Camera Usage Description, Privacy - Photo Library Usage Description을 권한접근허용을 해준다. 카메라는 시뮬레이터에서는 안돌아간다. 모델을 만드는게 가장 큰 일이다.

Reference

인프런 강의

Tags: ,

Categories:

Updated:

Leave a comment