Reputation: 411
I am writing some code for a little program in macOS to play with image processing with Metal Performance Shaders. For some reason, the code below produces an image that looks significantly darker than the original.
The code simply takes a texture, performs a little guassian blur on it, and then outputs the image to the MTKView. I cannot figure out why the resulting image is so dark, though.
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) {
}
}
What I did try to do on my own was to see if maybe for some reason the pixel format of the view being different mattered, as my input texture is a RGBA8UNorm_sRGB
while imageView.currentDrawable.texture
is a BGRA8UNorm
, however all of the examples of MPS don't really care what this pixel format is.
Input Image:
Weird Darker Output Image:
Upvotes: 4
Views: 1283
Reputation: 8356
This kind of darkening usually means that gamma correction is set up wrongly. Like you said in a comment, it can be fixed by option
[MTKTextureLoader.Option.SRGB : false]
Upvotes: 6