'CIMaskedVariableBlur creates unwanted border

I am using the following function to blur an image with depth map and noticed that the filter creates a border around the end result image. I am not sure what did I do wrongly that create this.

func blur(image: CIImage, mask: CIImage, orientation: UIImageOrientation = .up) -> UIImage? {
    
    let invertedMask = mask.applyingFilter("CIColorInvert")
    let output = image.applyingFilter("CIMaskedVariableBlur", parameters: ["inputMask" : invertedMask,"inputRadius": 15.0])
    
    guard let cgImage = context.createCGImage(output, from: output.extent) else {
        return nil
    }
    
    return UIImage(cgImage: cgImage, scale: 1.0, orientation: orientation)
}


Solution 1:[1]

I think you likely want to say:

func blur(image: CIImage, mask: CIImage, orientation: UIImageOrientation = .up) -> UIImage? {

    let invertedMask = mask.applyingFilter("CIColorInvert")
    let output = image.applyingFilter("CIMaskedVariableBlur", parameters: ["inputMask" : invertedMask,"inputRadius": 15.0])

    guard let cgImage = context.createCGImage(output, from: image.extent) else {
        return nil
    }

    return UIImage(cgImage: cgImage, scale: 1.0, orientation: orientation)
}

Where you are drawing in the extent of the original image. CIMaskedVariableBlur will set the extent to include all of the pixels sampled which will likely include pixels that you are not concerned particularly along the edges where color values are averaged with values outside the bounds of the original image.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 beyowulf