我仍然对如何制作由机器学习模型文件识别的当前图像(从图库照片中选择)感到困惑。我想做的是,一旦点击相机按钮,我就可以从图库图片中选择一张图片(这是代码的一部分)。但是,一旦显示照片,它不会触发 ml 模型,并且照片不会被识别,而是按原样显示。有人可以帮我吗?这是我的代码:
import SwiftUI
struct ContentView: View {
@State private var isShowPicker: Bool = false
@State private var image: Image? = Image("")
@State private var classificationLabel: String = ""
let model = MobileNetV2()
private func performImageClassification() {
let currentImageName = ImagePicker(image: self.$image)
guard let img = UIImage(named: "\(String(describing: currentImageName))"),
let resizedImage = img.resizeTo(size: CGSize(width: 224, height: 224)),
let pixelBuffer = resizedImage.toCVPixelBuffer() else {
return
}
let output = try? model.prediction(image: pixelBuffer)
if let output = output {
self.classificationLabel = output.classLabel
}
}
var body: some View {
NavigationView {
ZStack {
VStack {
image?
.resizable()
.navigationBarItems(trailing:
Button(action: {
self.performImageClassification()
self.isShowPicker.toggle()
})
{
Image(systemName: "camera.fill")
.font(.largeTitle)
}.foregroundColor(.blue)
).navigationBarBackButtonHidden(false)
.navigationBarTitle("\(classificationLabel)")
Text(classificationLabel)
Spacer()
}
}
.sheet(isPresented: $isShowPicker) {
ImagePicker(image: self.$image)
}
.navigationBarTitle(Text(classificationLabel))
}
}
}
struct ImagePicker: UIViewControllerRepresentable {
@Environment(\.presentationMode)
var presentationMode
@Binding var image: Image?
class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@Binding var presentationMode: PresentationMode
@Binding var image: Image?
init(presentationMode: Binding<PresentationMode>, image: Binding<Image?>) {
_presentationMode = presentationMode
_image = image
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let uiImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
image = Image(uiImage: uiImage)
presentationMode.dismiss()
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
presentationMode.dismiss()
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(presentationMode: presentationMode, image: $image)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController,
context: UIViewControllerRepresentableContext<ImagePicker>) {
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
ContentView()
}
}
}