1

I have an UIImage generated from a CanvasView. I want to use the featureprintObservationForImage feature on it. However it seems to take a URL and I am trying to provide a UIImage, how can I get around this?

Here is my code:

//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)!)

I am getting the error on the last line that says:

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

Any ideas?

0

1 Answer 1

1

Assuming that you need to get a VNFeaturePrintObservation instance, you could request an image instead of a URL by using the VNImageRequestHandler.

Assuming that featureprintObservationForImage method is (or looks something like this):

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
    }
}

You could have a different version as:

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
    }
  }

The differences in the second one are:

  • The signature of the method, takes an optional CIImage instead of a URL.

  • The initializer of the requestHandler.

Therefore:

let drawing = featureprintObservationForImage(image2?.ciImage)
Sign up to request clarification or add additional context in comments.

3 Comments

thank you, this seems to get rid of my error however the image2 now returns nil. this is in relation to 'picture VNFeaturePrintObservation? nil none'. any ideas on this one?
@kitchen800 well, not sure why the image is nil, but probably it seems a different issue; I'd suggest taking a look at the answers here
thanks i will have a look

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.