UIImage 到 URL 与 swift

UIImage to URL with swift

我有一个从 CanvasView 生成的 UIImage。 我想在上面使用 featureprintObservationForImage 功能。但是它似乎需要一个 URL 而我正在尝试提供一个 UIImage,我该如何解决这个问题?

这是我的代码:

//getting image
UIGraphicsBeginImageContextWithOptions(theCanvasView.bounds.size, false, UIScreen.main.scale)
        theCanvasView.drawHierarchy(in: theCanvasView.bounds, afterScreenUpdates: true)
        
        let image2 = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

//setting up observation for image
let drawing = featureprintObservationForImage(atURL: Bundle.main.url(image2)!)

我在最后一行收到错误消息:

Cannot convert value of type 'UIImage?' to expected argument type 'String'

有什么想法吗?

假设你需要得到一个VNFeaturePrintObservation instance, you could request an image instead of a URL by using the VNImageRequestHandler.

假设 featureprintObservationForImage 方法是(或看起来像这样):

func featureprintObservationForImage(atURL url: URL) -> VNFeaturePrintObservation? {
    let requestHandler = VNImageRequestHandler(url: url, options: [:])
    let request = VNGenerateImageFeaturePrintRequest()
    do {
        try requestHandler.perform([request])
        return request.results?.first as? VNFeaturePrintObservation
    } catch {
        print("Vision error: \(error)")
        return nil
    }
}

您可以使用不同的版本:

func featureprintObservationForImage(_ image: CIImage?) -> VNFeaturePrintObservation? {
    guard let ciImage = image else {
        return nil
    }
    let requestHandler = VNImageRequestHandler(ciImage: ciImage, options: [:])
    let request = VNGenerateImageFeaturePrintRequest()
    do {
      try requestHandler.perform([request])
      return request.results?.first as? VNFeaturePrintObservation
    } catch {
      print("Vision error: \(error)")
      return nil
    }
  }

第二个的区别是:

  • 方法的签名,采用可选的 CIImage 而不是 URL.

  • requestHandler 的初始值设定项。

因此:

let drawing = featureprintObservationForImage(image2?.ciImage)