MPSImageIntegral返回全零 [英] MPSImageIntegral returning all zeros

查看:160
本文介绍了MPSImageIntegral返回全零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用MPSImageIntegral计算MTLTexture中某些元素的总和.这就是我正在做的:

I am trying to use MPSImageIntegral to calculate the sum of some elements in an MTLTexture. This is what I'm doing:

std::vector<float> integralSumData;
for(int i = 0; i < 10; i++)
    integralSumData.push_back((float)i);

MTLTextureDescriptor *textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatR32Float
                                                                                             width:(integralSumData.size()) height:1 mipmapped:NO];
textureDescriptor.usage = MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite;
id<MTLTexture> texture = [_device newTextureWithDescriptor:textureDescriptor];

// Calculate the number of bytes per row in the image.
NSUInteger bytesPerRow = integralSumData.size() * sizeof(float);

MTLRegion region =
{
    { 0, 0, 0 },                   // MTLOrigin
    {integralSumData.size(), 1, 1} // MTLSize
};

// Copy the bytes from the data object into the texture
[texture replaceRegion:region
           mipmapLevel:0
             withBytes:integralSumData.data()
           bytesPerRow:bytesPerRow];


MTLTextureDescriptor *textureDescriptor2 = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatR32Float
                                                                                              width:(integralSumData.size()) height:1 mipmapped:NO];
textureDescriptor2.usage = MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite;
id<MTLTexture> outtexture = [_device newTextureWithDescriptor:textureDescriptor2];


// Create a MPS filter.
MPSImageIntegral *integral = [[MPSImageIntegral alloc] initWithDevice: _device];
MPSOffset offset = { 0,0,0};
[integral setOffset:offset];
[integral setEdgeMode:MPSImageEdgeModeZero];
[integral encodeToCommandBuffer:commandBuffer sourceTexture:texture destinationTexture:outtexture];

[commandBuffer commit];
[commandBuffer waitUntilCompleted];

但是,当我检查我的outtexture值时,其全为零.难道我做错了什么?这是我使用MPSImageIntegral的正确方法吗?

But, when I check my outtexture values, its all zeroes. Am I doing something wrong? Is this a correct way in which I shall use MPSImageIntegral?

我正在使用以下代码读取写入outTexture的值:

I'm using the following code to read values written into the outTexture:

float outData[100];
[outtexture getBytes:outData bytesPerRow:bytesPerRow fromRegion:region mipmapLevel:0];
for(int i = 0; i < 100; i++)
    std::cout << outData[i] << "\n";

谢谢

推荐答案

@Matthijis指出:我要做的就是使用MTLBlitEncoder确保在将MTLTexture读入CPU之前已对其进行同步,就像魅力一样!

As pointed out by @Matthijis: All I had to do was use an MTLBlitEncoder to make sure I synchronise my MTLTexture before reading it into CPU, and it worked like charm!

这篇关于MPSImageIntegral返回全零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆