如何不使深灰色透明从图像中删除背景

How to not cause dark gray color to be transparent removing background from image

我遇到一个问题,当我尝试从图像(在本例中为图像背景)中移除绿色时,所有深灰色(在我想要保留的图像部分内)都变成了半灰色透明的。我不确定为什么,想要一些关于如何做的建议:

    func chromaKeyFilter(fromHue: CGFloat, toHue: CGFloat) -> CIFilter? {
        let size = 64
        var cubeRGB = [Float]()

        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)

                    let color = UIColor(red: red, green: green, blue: blue, alpha: 1)
                    let hueColor = color.hsbColor
                    let alpha: CGFloat = (hueColor.hue >= fromHue && hueColor.hue <= toHue) ? 0 : 1
                    cubeRGB.append(Float(red * alpha))
                    cubeRGB.append(Float(green * alpha))
                    cubeRGB.append(Float(blue * alpha))
                    cubeRGB.append(Float(alpha))
                }
            }
        }

        let data = Data(bytes: cubeRGB, count: cubeRGB.count * MemoryLayout<Float>.size)
        let params: [String: Any] = ["inputCubeDimension": size, "inputCubeData": data]
        return CIFilter(name: "CIColorCube", parameters: params)
    }

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


extension UIColor {
    /// Decomposes UIColor to its HSBA components
    var hsbColor: HSBColor {
        var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
        self.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
        return HSBColor(hue: h, saturation: s, brightness: b, alpha: a)
    }

    /// Holds the CGFloat values of HSBA components of a color
    public struct HSBColor {
        var hue: CGFloat
        var saturation: CGFloat
        var brightness: CGFloat
        var alpha: CGFloat
    }
}

示例图片:

您的代码是正确的,但请记住,深灰色实际上可能是非常深的绿色。

这一行:

let alpha: CGFloat = (hueColor.hue >= fromHue && hueColor.hue <= toHue) ? 0 : 1

我会考虑 brightness/saturation。例如

let alpha: CGFloat = (hueColor.saturation > 0.1 && hueColor.hue >= fromHue && hueColor.hue <= toHue) ? 0 : 1