ios Swift中的图像文本识别

fhity93d  于 2022-12-20  发布在  iOS
关注(0)|答案(1)|浏览(249)

我是swift的新手,我想做一个可以解析截图的应用程序。到目前为止,我有下面的代码,我无法找出正确的方法来调用我的ContentView中的识别功能,任何帮助都是感激之情:'

struct ContentView: View {
    @State var selectedItems: PhotosPickerItem?
    @State var selectedPhotoData: Data?
    
    func recogText(selData: Data?)
    {
        if let selData = selData, let image = UIImage(data: selData){
            guard let cgImage = image.cgImage else {return}
            let handler = VNImageRequestHandler(cgImage: cgImage)
            let request = VNDetectTextRectanglesRequest { request, error in
                guard let observations = request.results as? [VNRecognizedTextObservation],
                      error == nil else {return}
                let text = observations.compactMap({
                    $0.topCandidates(1).first?.string
                    }).joined(separator: ", ")
                print(text.count)
            }
            
            do {
                try handler.perform([request])
            }
            catch {
                print("Unable to perform the requests: \(error).")
            }
        }
    }
    
    var body: some View {
        VStack{
            
           
            //Icon
            mainImage()
            
            //Button
            PhotosPicker(selection: $selectedItems, matching: .images) {
                Label("Select a photo", systemImage: "photo")
            }
            .tint(.blue)
            .controlSize(.large)
            .buttonStyle(.borderedProminent)
            .onChange(of: selectedItems) { newItem in
                Task {
                    if let data = try? await newItem?.loadTransferable(type: Data.self) {
                        selectedPhotoData = data
                        let _ = recogText(selData: data)
                    }
                }
            
            }
        }
    }
}

'
应打印已分析的文本,但未找到输出

xzv2uavs

xzv2uavs1#

你好,这里是一个示例函数,可能会对你有所帮助。当然,你必须用你的图像替换TestImage。这可能对你有用,你需要导入Vision

func recogText() {
    let textRecognitionRequest = VNRecognizeTextRequest { (request, error) in
        // Insert code to process the text recognition results here
        guard let observations = request.results as? [VNRecognizedTextObservation] else { return }

        for observation in observations {
            let topCandidate = observation.topCandidates(1).first
            if let recognizedText = topCandidate?.string {
                print(recognizedText)
            }
        }
    }
    
    textRecognitionRequest.recognitionLevel = .accurate
    
    let image = UIImage(named: "TestImage")
    let imageRequestHandler = VNImageRequestHandler(cgImage: (image?.cgImage!)!, options: [:])

    do {
        try imageRequestHandler.perform([textRecognitionRequest])
    } catch {
        print(error)
    }
}

相关问题