自定义Core Image过滤器颜色问题

时间:2016-06-24 10:39:14

标签: ios swift core-image cifilter cikernel

我正在学习如何编写自定义Core Image过滤器,但是当颜色值介于0 - 1之间时,渲染颜色与内核代码中指定的颜色不同,则会出现此问题。(等于0时颜色正确或者1。)

这是我的过滤器代码:

import UIKit
class testFilter: CIFilter
{   
    // simply return half red color (0.5)

    var colorKernel = CIColorKernel(string:
        "kernel vec4 theFilter()" +
        "{ return vec4(0.5, 0.0, 0.0, 1.0); }"
    )

    override var outputImage: CIImage!
    { 
        let rect = CGRect(x: 0, y: 0, width: 200, height: 100)
        return colorKernel.applyWithExtent(rect,arguments: nil)
    }
}

用法:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // generate image
        let filter = testFilter()
        let ciImage = f.outputImage      
        let image = UIImage(CIImage: ciImage) 

        // add to view
        let v = UIImageView(frame: CGRect(x: 50, y: 50, width: 200, height: 100))
        v.image = image     
        view.addSubview(v)
    }
}

输出图像如下所示,实际的红色分量值约为190(我使用Photoshop检查了颜色值)。对于0.5的值,我认为正确的输出值将是255 * 0.5 = 122.5?

the output image

1 个答案:

答案 0 :(得分:4)

我认为这是因为内核基于sRGB曲线创建颜色,并且您期望基于线性值的颜色。您可以将过滤器的输出更改为:

return colorKernel!.applyWithExtent(rect, arguments: nil)?
                   .imageByApplyingFilter("CISRGBToneCurveToLinear", withInputParameters: nil)

更正输出颜色。顺便说一下,通道是UInt8,因此值是整数,半红色值是127.