前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Metal入门教程(四)灰度计算

Metal入门教程(四)灰度计算

作者头像
落影
发布2020-10-26 10:29:25
1.4K0
发布2020-10-26 10:29:25
举报
文章被收录于专栏:落影的专栏

前言

Metal入门教程(一)图片绘制

Metal入门教程(二)三维变换

Metal入门教程(三)摄像头采集渲染

前面的教程介绍了Metal如何显示图片、自定义shader实现三维变换以及用MetalPerformanceShaders处理摄像头数据,这次尝试创建计算管道,实现Metal的compute shader。

Metal系列教程的代码地址

OpenGL ES系列教程在这里

你的star和fork是我的源动力,你的意见能让我走得更远

正文

Metal的计算管道只有一个步骤,就是kernel function(内核函数)。相对于渲染管道,其需要经过多个步骤处理:

kernel function(内核函数)可直接读取资源,计算处理后输出到对应位置。

核心思路

创建计算管道和渲染管道,加载一张图片到Metal得到sourceTexture,用计算管道对sourceTexture进行处理,然后结果输出到destTexture,最后用渲染管道把destTexture显示到屏幕上。

效果展示
具体步骤
1、设置渲染管道和计算管道
代码语言:javascript
复制
// 设置渲染管道和计算管道
-(void)setupPipeline {
    id<MTLLibrary> defaultLibrary = [self.mtkView.device newDefaultLibrary]; // .metal
    id<MTLFunction> vertexFunction = [defaultLibrary newFunctionWithName:@"vertexShader"]; // 顶点shader,vertexShader是函数名
    id<MTLFunction> fragmentFunction = [defaultLibrary newFunctionWithName:@"samplingShader"]; // 片元shader,samplingShader是函数名
    id<MTLFunction> kernelFunction = [defaultLibrary newFunctionWithName:@"sobelKernel"];
    
    MTLRenderPipelineDescriptor *pipelineStateDescriptor = [[MTLRenderPipelineDescriptor alloc] init];
    pipelineStateDescriptor.vertexFunction = vertexFunction;
    pipelineStateDescriptor.fragmentFunction = fragmentFunction;
    pipelineStateDescriptor.colorAttachments[0].pixelFormat = self.mtkView.colorPixelFormat;
    // 创建图形渲染管道,耗性能操作不宜频繁调用
    self.renderPipelineState = [self.mtkView.device newRenderPipelineStateWithDescriptor:pipelineStateDescriptor
                                                                                   error:NULL];
    // 创建计算管道,耗性能操作不宜频繁调用
    self.computePipelineState = [self.mtkView.device newComputePipelineStateWithFunction:kernelFunction
                                                                                   error:NULL];
    // CommandQueue是渲染指令队列,保证渲染指令有序地提交到GPU
    self.commandQueue = [self.mtkView.device newCommandQueue];
}

渲染管道的创建与之前相同;

-newComputePipelineStateWithFunction:可以创建计算管道,方法仅需要一个参数,就是内核函数。

2、设置顶点
代码语言:javascript
复制
- (void)setupVertex {
    const LYVertex quadVertices[] =
    {   // 顶点坐标,分别是x、y、z、w;    纹理坐标,x、y;
        { {  0.5, -0.5 / self.viewportSize.height * self.viewportSize.width, 0.0, 1.0 },  { 1.f, 1.f } },
        { { -0.5, -0.5 / self.viewportSize.height * self.viewportSize.width, 0.0, 1.0 },  { 0.f, 1.f } },
        { { -0.5,  0.5 / self.viewportSize.height * self.viewportSize.width, 0.0, 1.0 },  { 0.f, 0.f } },
        
        { {  0.5, -0.5 / self.viewportSize.height * self.viewportSize.width, 0.0, 1.0 },  { 1.f, 1.f } },
        { { -0.5,  0.5 / self.viewportSize.height * self.viewportSize.width, 0.0, 1.0 },  { 0.f, 0.f } },
        { {  0.5,  0.5 / self.viewportSize.height * self.viewportSize.width, 0.0, 1.0 },  { 1.f, 0.f } },
    };
    self.vertices = [self.mtkView.device newBufferWithBytes:quadVertices
                                                     length:sizeof(quadVertices)
                                                    options:MTLResourceStorageModeShared]; // 创建顶点缓存
    self.numVertices = sizeof(quadVertices) / sizeof(LYVertex); // 顶点个数
}

为使得图像显示不拉伸,对顶点做一个简单处理。

3、设置纹理
代码语言:javascript
复制
- (void)setupTexture {
    UIImage *image = [UIImage imageNamed:@"abc"];
    // 纹理描述符
    MTLTextureDescriptor *textureDescriptor = [[MTLTextureDescriptor alloc] init];
    textureDescriptor.pixelFormat = MTLPixelFormatRGBA8Unorm; // 图片的格式要和数据一致
    textureDescriptor.width = image.size.width;
    textureDescriptor.height = image.size.height;
    textureDescriptor.usage = MTLTextureUsageShaderRead; // 原图片只需要读取
    self.sourceTexture = [self.mtkView.device newTextureWithDescriptor:textureDescriptor]; // 创建纹理
    
    MTLRegion region = {{ 0, 0, 0 }, {image.size.width, image.size.height, 1}}; // 纹理上传的范围
    Byte *imageBytes = [self loadImage:image];
    if (imageBytes) { // UIImage的数据需要转成二进制才能上传,且不用jpg、png的NSData
        [self.sourceTexture replaceRegion:region
                        mipmapLevel:0
                          withBytes:imageBytes
                        bytesPerRow:4 * image.size.width];
        free(imageBytes); // 需要释放资源
        imageBytes = NULL;
    }
    
    textureDescriptor.usage = MTLTextureUsageShaderWrite | MTLTextureUsageShaderRead; // 目标纹理在compute管道需要写,在render管道需要读
    self.destTexture = [self.mtkView.device newTextureWithDescriptor:textureDescriptor];
}

共需要创建两个纹理,先创建输入的纹理sourceTexture,再用相同的描述符加上MTLTextureUsageShaderWrite属性创建输出的纹理destTexture。

4、设置计算区域
代码语言:javascript
复制
- (void)setupThreadGroup {
    self.groupSize = MTLSizeMake(16, 16, 1); // 太大某些GPU不支持,太小效率低;
    
    //保证每个像素都有处理到
    _groupCount.width  = (self.sourceTexture.width  + self.groupSize.width -  1) / self.groupSize.width;
    _groupCount.height = (self.sourceTexture.height + self.groupSize.height - 1) / self.groupSize.height;
    _groupCount.depth = 1; // 我们是2D纹理,深度设为1
}

这里设置的是计算管道中每次处理的大小groupSize,size不能太大会导致某些GPU不支持,而太小则效率会低;groupCount是计算的次数,需要保证足够大,以便每个像素都能处理。

5、渲染处理
代码语言:javascript
复制
    // 每次渲染都要单独创建一个CommandBuffer
    id<MTLCommandBuffer> commandBuffer = [self.commandQueue commandBuffer];
    {
        // 创建计算指令的编码器
        id<MTLComputeCommandEncoder> computeEncoder = [commandBuffer computeCommandEncoder];
        // 设置计算管道,以调用shaders.metal中的内核计算函数
        [computeEncoder setComputePipelineState:self.computePipelineState];
        // 输入纹理
        [computeEncoder setTexture:self.sourceTexture
                           atIndex:LYFragmentTextureIndexTextureSource];
        // 输出纹理
        [computeEncoder setTexture:self.destTexture
                           atIndex:LYFragmentTextureIndexTextureDest];
        // 计算区域
        [computeEncoder dispatchThreadgroups:self.groupCount
                       threadsPerThreadgroup:self.groupSize];
        // 调用endEncoding释放编码器,下个encoder才能创建
        [computeEncoder endEncoding];
    }

MTLComputeCommandEncoder是计算指令的编码器,用于编码接下来的指令;首先设置计算管道computePipelineState,再设置相关的参数,最后用dispatchThreadgroups:self启动计算。(记得最后要加endEncoding

6、Shader逻辑
代码语言:javascript
复制
constant half3 kRec709Luma = half3(0.2126, 0.7152, 0.0722); // 把rgba转成亮度值

kernel void
grayKernel(texture2d<half, access::read>  sourceTexture  [[texture(LYFragmentTextureIndexTextureSource)]],
                texture2d<half, access::write> destTexture [[texture(LYFragmentTextureIndexTextureDest)]],
                uint2                          grid         [[thread_position_in_grid]])
{
    // 边界保护
    if(grid.x <= destTexture.get_width() && grid.y <= destTexture.get_height())
    {
        half4 color  = sourceTexture.read(grid); // 初始颜色
        half  gray     = dot(color.rgb, kRec709Luma); // 转换成亮度
        destTexture.write(half4(gray, gray, gray, 1.0), grid); // 写回对应纹理
    }
}

灰度计算的shader如上,kRec709Luma是rgb转亮度值用到的常量;

grayKernel的参数有三个,分别是输入的纹理、输出的纹理、索引下标。

grid有两个值,分别是x和y,表明当前计算shader处理的像素点位置。每次内核函数执行,都会有一个唯一的grid值。

通过sourceTexture.read(grid)可以读取输入纹理的颜色,处理后再通过destTexture.write的方法写入输出纹理。

总结

内核函数的执行次数需要事先指定,这个次数由格子大小决定。

threadgroup 指的是设定的处理单元,demo里是16*16;这个值要根据具体的设备进行区别,但16*16是足够小的,能让所有的GPU执行;

threadgroupCount 是需要处理的次数,一般来说threadgroupCount*threadgroup=需要处理的大小。

MTLComputePipelineState 代表一个计算处理管道,只需要一个内核函数就可以创建,相比之下,渲染管道需要顶点和片元两个处理函数。

Demo的地址在这里

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.07.14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 正文
    • 核心思路
      • 效果展示
        • 具体步骤
          • 1、设置渲染管道和计算管道
          • 2、设置顶点
          • 3、设置纹理
          • 4、设置计算区域
          • 5、渲染处理
          • 6、Shader逻辑
      • 总结
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档