使用CIAdditionCompositing叠加纯黑图像为何结果不符合预期?
Why CIAdditionCompositing Made Your Gray Image Brighter Than Expected
Great question—this is a classic gotcha with Core Image tied to color space handling, so let's unpack what's happening here.
The Root Cause: Linear vs. Non-Linear RGB
Core Image runs almost all its operations, including CIAdditionCompositing, in a linear RGB color space. The catch is that most standard image formats (like sRGB) use a non-linear curve to encode brightness, since human vision doesn't perceive light linearly.
Here's the step-by-step breakdown of what likely went wrong for you:
- When you created your mid-gray image, you probably used a value like
0.5thinking it's sRGB (which maps to an 8-bit pixel of 128, the "middle" gray we visually recognize). - But Core Image automatically converts that sRGB value to linear RGB for processing:
0.5(sRGB) translates to roughly0.218in linear RGB. CIAdditionCompositingadds the linear values:0.218 + 0 = 0.218(still linear RGB).- The problem hits when you view the result: if your pipeline doesn't convert the linear value back to sRGB, or if you accidentally defined your gray as linear RGB to begin with, the output looks brighter. For example:
- If you defined your gray as
0.5in linear RGB (not sRGB), that's equivalent to ~0.729in sRGB (≈ 186 in 8-bit)—way brighter than the mid-gray you expected. Adding black doesn't change that linear value, so the output stays bright.
- If you defined your gray as
How to Fix This
To get the exact mid-gray you're expecting, make sure your input images are tied to the sRGB color space explicitly:
- When creating colored images in code, specify sRGB instead of relying on defaults:
let sRGBSpace = CGColorSpace(name: CGColorSpace.sRGB)! let grayColor = CIColor(color: CGColor(gray: 0.5, alpha: 1.0, colorSpace: sRGBSpace)) let grayImage = CIImage(color: grayColor) - After compositing, ensure the output image is converted back to sRGB before displaying or exporting it.
Quick Test to Confirm
Check the raw pixel values of your composite image:
- If it's the correct mid-gray, you'll see an 8-bit value of 128.
- If it's brighter, you'll see a value around 186—confirming your input gray was treated as linear RGB instead of sRGB.
内容的提问来源于stack exchange,提问作者stkent
相关产品推荐
相关产品推荐

