I'm using the following code to remove green background from an image.But the edges of the image has green tint to it and some pixels are damaged.How can i smoothen this and make the cut out perfect.
func chromaKeyFilter(fromHue: CGFloat, toHue: CGFloat) -> CIFilter?
{
// 1
let size = 64
var cubeRGB = [Float]()
// 2
for z in 0 ..< size {
let blue = CGFloat(z) / CGFloat(size-1)
for y in 0 ..< size {
let green = CGFloat(y) / CGFloat(size-1)
for x in 0 ..< size {
let red = CGFloat(x) / CGFloat(size-1)
// 3
let hue = getHue(red: red, green: green, blue: blue)
let alpha: CGFloat = (hue >= fromHue && hue <= toHue) ? 0: 1
// 4
cubeRGB.append(Float(red * alpha))
cubeRGB.append(Float(green * alpha))
cubeRGB.append(Float(blue * alpha))
cubeRGB.append(Float(alpha))
}
}
}
@IBAction func clicked(_ sender: Any) {
let a = URL(fileURLWithPath:"green.png")
let b = URL(fileURLWithPath:"back.jpg")
let image1 = CIImage(contentsOf: a)
let image2 = CIImage(contentsOf: b)
let chromaCIFilter = self.chromaKeyFilter(fromHue: 0.3, toHue: 0.4)
chromaCIFilter?.setValue(image1, forKey: kCIInputImageKey)
let sourceCIImageWithoutBackground = chromaCIFilter?.outputImage
/*let compositor = CIFilter(name:"CISourceOverCompositing")
compositor?.setValue(sourceCIImageWithoutBackground, forKey: kCIInputImageKey)
compositor?.setValue(image2, forKey: kCIInputBackgroundImageKey)
let compositedCIImage = compositor?.outputImage*/
var rep: NSCIImageRep = NSCIImageRep(ciImage: sourceCIImageWithoutBackground!)
var nsImage: NSImage = NSImage(size: rep.size)
nsImage.addRepresentation(rep)
let url = URL(fileURLWithPath:"file.png")
nsImage.pngWrite(to: url)
super.viewDidLoad()
}
Input:
macOS
, i have used CIImage while the OSX sample uses UIImage. – Roslyn