Ezaldeen99 / BackgroundRemoval

Background Removal written with swift using u2net model
Apache License 2.0
203 stars 34 forks source link

Background still visible when I save UIImage as Data #2

Closed LucaComanducci closed 2 years ago

LucaComanducci commented 2 years ago

Hi, thanks a lot for your work, it's great, I'm finding it really useful. I'm having an issue when I try to save image as Data:

let image = UIImage(named: "myImage")!

// transparent background
let resultImage = BackgroundRemoval().removeBackground(image: image)

let resultData = resultImage.pngData()!

// background is visible
let resultImage2 = UIImage(data: resultData)

In the previous example the resultImage2 image contains the original background. Is background information really removed from the object? it seems like information is still saved in resultImage for some reasons.

Ezaldeen99 commented 2 years ago

hello and thanks for reporting this issue.

this is happening because the result image is just a mask result between the mask and the input. however, if you want to get. the data please refer to the solution below

         let resultImage = BackgroundRemoval().removeBackground(image: image!)

        let newImage2 = drawImage(resultImage)
        let newImage = UIImage(data: newImage2!.pngData()!)

        // background is visible

        outputImage.image = newImage

where the draw function is

  func drawImage(_ image: UIImage) -> UIImage?
        {
            guard let coreImage = image.cgImage else {
                return nil;
            }
            UIGraphicsBeginImageContext(CGSize(width: coreImage.width, height: coreImage.height))
            image.draw(in: CGRect(x: Int(0.0), y: Int(0.0), width: coreImage.width, height: coreImage.height))
            let resultImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            return resultImage;
        }

ref: https://stackoverflow.com/questions/53967126/cgimage-masking-with-uiimage-pngdata

please reopen the issue if you have any other problems with this apporach