Aarfeen Ahmad
Aarfeen Ahmad

Reputation: 76

Extracting the Outline Path from an Image with a Transparent Background, Swift | SwiftUI

I'm using the Vision framework to obtain a masked image and an image with a transparent background. I want to extract the outline path of the image using contour detection.

Here’s the function I'm using:

private func detectContours(image: UIImage) async throws -> CGPath? {
// Convert UIImage to CIImage
guard let ciImage = CIImage(image: image) else {
    return nil
}

// Set up the contour detection request
var request = DetectContoursRequest()
request.contrastAdjustment = 1.5
request.contrastPivot = nil

// Perform the contour detection request
let contoursObservations = try await request.perform(
    on: ciImage,
    orientation: .downMirrored
)

// Retrieve the detected contours as a path object
let contours = contoursObservations.normalizedPath

return contours
}

This is how I'm using it

 Task {
            do {
                contours = try await detectContours(image: maskedImage)
            } catch {
                print("Error detecting contours: \(error)")
            }
        }

This function returns the desired contours, but it also includes an extra path representing the image frame. How can I modify this function to exclude the frame path and only return the contours of the actual content?

This is Mask Image mask image

This is path image path image

Upvotes: 0

Views: 27

Answers (1)

Aarfeen Ahmad
Aarfeen Ahmad

Reputation: 76

I just inverted the color of the mask with the help of this function and it is working perfectly.

    func invertColors(of ciImage: CIImage) -> CIImage? {
    let invertFilter = CIFilter(name: "CIColorInvert")
    invertFilter?.setValue(ciImage, forKey: kCIInputImageKey)


    return invertFilter?.outputImage
}

Upvotes: 0

Related Questions