使用MPSImageConvolution时发生异常

时间:2018-12-12 20:18:07

标签: ios swift swift4 gpu metal

我正在尝试使用MPSImageConvolution进行一些图像过滤并不断收到错误:“在wt [0]的索引1处缺少缓冲区绑定”。 在MPSImageLaplacian中使用相同的代码时,它可以正常工作。

这是我的代码:

    let img = UIImage(named: "some-image")!
    // convert to single channel grayscale and scale to half-size
    let image = toGrayscale(cgImage: img.cgImage!, scale: 2)

    let cmdQ: MTLCommandQueue! = device.makeCommandQueue()
    let commandBuffer = cmdQ.makeCommandBuffer()!

    let textureLoader = MTKTextureLoader(device: device)
    let options: [MTKTextureLoader.Option : Any]? = nil // [ MTKTextureLoader.Option.SRGB : NSNumber(value: false) ]
    let srcTex = try! textureLoader.newTexture(cgImage: image.cgImage!, options: options)

    let lapKernel: [Float] =
    [
        0.0, 1.0, 0.0,
        1.0, -4.0, 1.0,
        0.0, 1.0, 0.0
    ];

    let unsafeArray: UnsafePointer<Float> = UnsafePointer<Float>(lapKernel)

    let desc = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: srcTex.pixelFormat,
                                                              width: srcTex.width,
                                                              height: srcTex.height,
                                                              mipmapped: false)
    desc.usage.formUnion(.shaderWrite)
    let lapTex = device.makeTexture(descriptor: desc)

    //  let lapConv = MPSImageLaplacian(device: device) <-- Using this works fine
    let lapConv = MPSImageConvolution(device: device, kernelWidth: 3, kernelHeight: 3, weights: unsafeArray)
    lapConv.encode(commandBuffer: commandBuffer, sourceTexture: srcTex, destinationTexture: lapTex!)

以上代码片段的最后一行崩溃,并显示以下错误:

  

validateComputeFunctionArguments:811:断言失败`Compute Function(k_1x3_R_1x_5y_f):缺少wt [0]在索引1处的缓冲区绑定。

任何想法可能是什么问题?除此之外,我还使用中值过滤器和阈值过滤器,并且一切正常 谢谢!

1 个答案:

答案 0 :(得分:0)

我有相同的断言异常:

Compute Function(k_1x3_R_1x_5y_f): missing buffer binding at index 1 for wt[0].

...使用MPSImageConvolution时。我修改了内核,使矩阵中的零值变为0.0001。您可以将lapKernel更改为:

   let lapKernel: [Float] =
    [
        0.0001, 1.0, 0.0001,
        1.0, -4.0, 1.0,
        0.0001, 1.0, 0.0001
    ]

...我发现它避免了断言异常,希望不会显着改变图像过滤器的功能。

在您的示例中,;之后的lapKernel是多余的(如果我要说明显的话,我们深表歉意)