我正在从包含至少一个人体的图像中删除背景。我将蒙版应用于UIImage并成功蒙版了仅包含具有透明背景的人体的图像,但是如果我尝试在应用蒙版后转换回UIImage,则会得到黑白裁剪图像。
我正在使用此代码段应用蒙版并以UIImage的形式获取结果
func maskImage(image:UIImage, mask:(UIImage))->UIImage{
let imageReference = image.cgImage
let maskReference = mask.cgImage
let imageMask = CGImage(maskWidth: maskReference!.width,
height: maskReference!.height,
bitsPerComponent: maskReference!.bitsPerComponent,
bitsPerPixel: maskReference!.bitsPerPixel,
bytesPerRow: maskReference!.bytesPerRow,
provider: maskReference!.dataProvider!, decode: nil, shouldInterpolate: true)
let maskedReference = imageReference!.masking(imageMask!)
let maskedImage = UIImage(cgImage:maskedReference!)
return maskedImage
}
但是我得到的是只有人体而不是彩色的黑白图像。
答案 0 :(得分:0)
经过大量研究,我终于得到如下答案:
UIGraphicsBeginImageContextWithOptions(imgView1.frame.size, _: false, _: 0.0)
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: 0.0, y: (imgView1?.frame.size.height)!)
context?.scaleBy(x: 1.0, y: -1.0)
let maskImage = maskImg.cgImage
context?.clip(to: imgView1!.bounds, mask: maskImage!)
context?.translateBy(x: 0.0, y: (imgView1?.frame.size.height)!)
context?.setStrokeColor(UIColor.red.cgColor)
context?.stroke(imgView1!.frame, width: 15.0)
context?.scaleBy(x: 1.0, y: -1.0)
imgView1?.image?.draw(in: imgView1?.bounds ?? CGRect.zero)
let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()