1

I wanted to change all the white background of a grayscale line art to transparent, using swift. I implemented RGB chromakey document for swift: https://developer.apple.com/documentation/coreimage/applying_a_chroma_key_effect

The hue range was initially for green color and there were R,G,B and alpha parameters

self.ChromaKeyFilter(fromHue: 0.3, toHue: 0.4)

, but for grayscale there were only 2 according to apple documentation: white, alpha. I wanted to change the extreme white color to transparent, so I just set hue range as 1.

class ChromaKey{

    //Hue range

    let whiteRange: CGFloat = 1

    func getHue(white: CGFloat) -> CGFloat{
        let color = UIColor(white: white, alpha: 1)
        var hue: CGFloat = 0
        color.getHue(&hue, saturation: nil, brightness: nil, alpha: nil)
        return hue
    }

    func chromaKeyFilter(ridHue:CGFloat) -> CIFilter? {
        let size = 64
        var cubeGrey = [Float]()

        for z in 0 ..< size{
            let white = CGFloat(z)/CGFloat(size-1)

            let hue = getHue(white: white)
            let alpha: CGFloat = (hue == ridHue) ? 0:1

            cubeGrey.append(Float(white * alpha))
            cubeGrey.append(Float(alpha))

        }
        let data = Data(buffer: UnsafeBufferPointer(start: &cubeGrey, count: cubeGrey.count))

        let colorCubeFilter = CIFilter(name: "CIColorCube", parameters: ["inputCubeDimension": size, "inputCubeData":data])
        return colorCubeFilter
    }

func filterPixels(foregroundCIImage: CIImage) -> CIImage {
        let chromaCIFilter = self.chromaKeyFilter(ridHue: whiteRange)
        chromaCIFilter?.setValue(foregroundCIImage, forKey: kCIInputImageKey)
        let sourceCIImageWithoutBackground = chromaCIFilter?.outputImage
        var image = CIImage()
        if let filteredImage = sourceCIImageWithoutBackground{
            image = filteredImage
        }
        return image
    }

the func for chromakey. when I apply the func, nothing shows up.

Say
  • 74
  • 6

0 Answers0