0

I have a function which is meant to return an optional CGImage but on the line return croppedImage I am receiving a compilation error: Cannot convert value of type 'CGImage' to closure result type 'Void' How can I return the CGImage from the closure and why is this error happening?

func findRectangleAndCropImage(_ image: CGImage) -> CGImage? {
        // Create a request to detect rectangles
        let request = VNDetectRectanglesRequest { [weak self] request, error in
            guard let observations = request.results as? [VNRectangleObservation], let firstObservation = observations.first else {
                return
            }
            
            // Convert the rectangle observation to a CGRect
            let boundingBox = firstObservation.boundingBox
            let imageSize = CGSize(width: CGFloat(image.width), height: CGFloat(image.height))
            let transformedRect = VNImageRectForNormalizedRect(boundingBox, Int(imageSize.width), Int(imageSize.height))
            let rectInt = transformedRect.integral
            
            // Create a new image by cropping the original image using the rectangle
            if let croppedImage = image.cropping(to: rectInt) {
                // Compiler error: Cannot convert value of type 'CGImage' to closure result type 'Void'
                return croppedImage
            }
        }
        
        // Create a request handler for the image
        let requestHandler = VNImageRequestHandler(cgImage: image, options: [:])
        
        do {
            // Perform the rectangle detection
            try requestHandler.perform([request])
        } catch {
            print("Error: \(error)")
        }
        
        return nil
    }
etayluz
  • 15,920
  • 23
  • 106
  • 151
  • `VNDetectRectanglesRequest` is an asynchronous function. You can't `return` an image from your function. – Paulw11 May 25 '23 at 05:23

0 Answers0