2017-06-15 76 views
10

我使用iOS 11的視覺框架來檢測圖像上的文字。文本已成功檢測到,但我們如何獲取檢測到的文本。iOS 11視覺框架 - 從圖像中提取文字

+0

您現在需要使用CoreML併發送要讀取的區域 –

+0

@Alex已獲取要檢測的區域。需要解決方案來讀取檢測到的區域。 – Abhishek

+1

[將視覺VNTextObservation轉換爲字符串]的可能重複(https://stackoverflow.com/questions/44533148/converting-a-vision-vntextobservation-to-a-string) –

回答

-4

這將返回一個覆蓋圖像與矩形框中檢測到的文本

以下是完整的Xcode項目 https://github.com/cyruslok/iOS11-Vision-Framework-Demo

希望這是有幫助的

// Text Detect 
func textDetect(dectect_image:UIImage, display_image_view:UIImageView)->UIImage{ 
    let handler:VNImageRequestHandler = VNImageRequestHandler.init(cgImage: (dectect_image.cgImage)!) 
    var result_img:UIImage = UIImage.init(); 

    let request:VNDetectTextRectanglesRequest = VNDetectTextRectanglesRequest.init(completionHandler: { (request, error) in 
     if((error) != nil){ 
      print("Got Error In Run Text Dectect Request"); 

     }else{ 
      result_img = self.drawRectangleForTextDectect(image: dectect_image,results: request.results as! Array<VNTextObservation>) 
     } 
    }) 
    request.reportCharacterBoxes = true 
    do { 
     try handler.perform([request]) 
     return result_img; 
    } catch { 
     return result_img; 
    } 
} 

func drawRectangleForTextDectect(image: UIImage, results:Array<VNTextObservation>) -> UIImage { 
    let renderer = UIGraphicsImageRenderer(size: image.size) 
    var t:CGAffineTransform = CGAffineTransform.identity; 
    t = t.scaledBy(x: image.size.width, y: -image.size.height); 
    t = t.translatedBy(x: 0, y: -1); 

    let img = renderer.image { ctx in 
     for item in results { 
      let TextObservation:VNTextObservation = item 
      ctx.cgContext.setFillColor(UIColor.clear.cgColor) 
      ctx.cgContext.setStrokeColor(UIColor.green.cgColor) 
      ctx.cgContext.setLineWidth(1) 
      ctx.cgContext.addRect(item.boundingBox.applying(t)) 
      ctx.cgContext.drawPath(using: .fillStroke) 

      for item_2 in TextObservation.characterBoxes!{ 
       let RectangleObservation:VNRectangleObservation = item_2 
       ctx.cgContext.setFillColor(UIColor.clear.cgColor) 
       ctx.cgContext.setStrokeColor(UIColor.red.cgColor) 
       ctx.cgContext.setLineWidth(1) 
       ctx.cgContext.addRect(RectangleObservation.boundingBox.applying(t)) 
       ctx.cgContext.drawPath(using: .fillStroke) 
      } 
     } 

    } 
    return img 
} 
+2

你有沒有讀過這個問題? – Tech