我正在为一个在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_sRGB
而 imageView.currentDrawable.texture
是 BGRA8UNorm
,但是所有 MPS 的示例似乎并不在意这种像素格式。
MPSBilinearScaling
或MPSTranspose
,也会导致颜色较暗的图像。 - DaveNineMTLTextureLoader
添加选项[MTKTextureLoader.Option.SRGB:false]
。我现在感觉很傻,因为我先问问题,后来才自己解决了它。我将保留这个问题,以防其他人遇到相同的问题,看起来纹理装载器经常会出现这种情况! - DaveNine