【发布时间】:2018-05-24 12:53:06
【问题描述】:
我正在为 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 的所有示例并不真正关心这种像素格式是什么。
【问题讨论】:
-
你有没有试过看看如果你不做高斯模糊会发生什么?天还黑吗?
-
@DaveWeston 确实如此,即使像
MPSBilinearScaling或MPSTranspose这样对图像执行线性变换也会导致图像颜色变深。 -
呃,当然 -__- 它是 SRGB!如果你给
MTLTextureLoader选项[MTKTextureLoader.Option.SRGB : false]。我只是觉得问我的问题然后再想出来很傻。我会保留它以防其他人遇到同样的事情,这似乎是纹理加载器的常见实例! -
@DavidSacco 请为解释问题的问题写一个答案,然后接受它。
标签: ios swift macos image-processing metal