金属纹理比原始图像更暗

4

我正在为一个在macOS上与Metal Performance Shaders玩耍的图像处理小程序编写一些代码。由于某种原因,下面的代码产生的图像看起来比原始图像要暗得多。

该代码简单地取一个纹理,在其上执行一些高斯模糊,然后将图像输出到MTKView中。我无法弄清楚为什么结果图像如此暗淡。

import Cocoa
import Metal
import MetalKit
import CoreGraphics
import MetalPerformanceShaders


class ViewController: NSViewController, MTKViewDelegate {
@IBOutlet weak var imageView: MTKView!
override func viewDidLoad() {
    super.viewDidLoad()

    //Setup the Metal Pipeline
    let device = MTLCreateSystemDefaultDevice()!
    imageView.device = device
    imageView.framebufferOnly = false
    imageView.isPaused = true
    let commandQueue = device.makeCommandQueue()!
    let commandBuffer = commandQueue.makeCommandBuffer()!
    let gaussian = MPSImageGaussianBlur(device: device, sigma: 2)
    let data = imageData(name:"sample", type:"jpg")

    let inputTexture = try! MTKTextureLoader(device: device).newTexture(data: data, options: nil)

    gaussian.encode(commandBuffer: commandBuffer, sourceTexture: inputTexture, destinationTexture: (imageView.currentDrawable?.texture)!)
    commandBuffer.present(imageView.currentDrawable!)
    commandBuffer.commit()
}

func imageData(name: String, type: String) -> Data {
    let urlpath = Bundle.main.path(forResource: name, ofType: type)!
    let url = NSURL.fileURL(withPath: urlpath)
    var data : Data? = nil
    do{ try data = Data(contentsOf: url)}
    catch{print("Couldn't set data.")}
    return data!
}

override var representedObject: Any? {
    didSet {
    // Update the view, if already loaded.
    }
}
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {

}
func draw(in view: MTKView) {
}

我个人尝试的是检查视图的像素格式是否不同,因为我的输入纹理是 RGBA8UNorm_sRGBimageView.currentDrawable.textureBGRA8UNorm,但是所有 MPS 的示例似乎并不在意这种像素格式。

输入图片:enter image description here 奇怪的较暗输出图片:enter image description here


你尝试过不对它进行高斯模糊会发生什么吗?它还是暗的吗? - Dave Weston
@DaveWeston 确实如此,即使对图像执行线性变换,如 MPSBilinearScalingMPSTranspose,也会导致颜色较暗的图像。 - DaveNine
6
当然,真是太糟糕了 -__- 这是SRGB的问题!!如果你给MTLTextureLoader添加选项[MTKTextureLoader.Option.SRGB:false]。我现在感觉很傻,因为我先问问题,后来才自己解决了它。我将保留这个问题,以防其他人遇到相同的问题,看起来纹理装载器经常会出现这种情况! - DaveNine
@DavidSacco 请为这个问题编写一个答案,解释其中的问题,并随后接受它。 - Tamás Sengel
1个回答

6
这种变暗通常意味着伽马校正设置不正确。就像您在评论中所说的那样,可以通过选项来修复它。
[MTKTextureLoader.Option.SRGB : false]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接