Object Detection Model returns empty dictionary of results

I have made a object detection model and when I load my model in xcode I can see the expected results when inputing an image in the preview page of the model. However, when I am trying to use the model in my code it is return 0 detections, however when i put the same image in preview it returns expected result? Anyone know what could be wrong?

func detectLeaf(in image: UIImage) -> Int {
        var leafDetected = 0
        guard let modelURL = Bundle.main.url(forResource: "LeafModel", withExtension: "mlmodelc") else {
            print("Model file is missing")
            return leafDetected
        }
        do {
            let visionModel = try VNCoreMLModel(for: MLModel(contentsOf: modelURL))
            let objectRecognition = VNCoreMLRequest(model: visionModel) { request, error in
                if let results = request.results {
                    print(results.count)
                    print(results)
                    leafDetected = results.count
                }
            }
            let handler = VNImageRequestHandler(cgImage: image.cgImage!)
            try handler.perform([objectRecognition])
            return leafDetected

        } catch {
            print("Error loading model: \(error.localizedDescription)")
            return 0
        }
    }

Hello,

Usually this sort of issue indicates a problem with how the input image is being provided to the model. For example, it's possible that the CGImage you are providing has lost orientation metadata, and so the model is running in your app with a different (rotated) input compared to the model preview.

To confirm this theory, try providing an explicit orientation to the request handler that matches your input. If you start getting results, you should look into using a code path that preserves the orientation metadata of the input image.

Hi, thank you for your response. The orientation metadata is preserved. Any other ideas on what could be causing this problem?

Object Detection Model returns empty dictionary of results
 
 
Q