我正在为 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) {
}
我自己尝试做的是看看是否由于某种原因 View 的像素格式不同很重要,因为我的输入纹理是 RGBA8UNorm_sRGB
而 imageView. currentDrawable.texture
是一个 BGRA8UNorm
,但是 MPS 的所有示例并不真正关心这种像素格式是什么。
最佳答案
这种变暗通常意味着 Gamma 校正设置错误。正如您在评论中所说,它可以通过选项修复
[MTKTextureLoader.Option.SRGB : false]
关于ios - Metal 质感比原图暗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47745486/