Metal入門教程(三)攝像頭采集渲染

前言

Metal入門教程(一)圖片繪制
Metal入門教程(二)三維變換

前面的教程介紹了如何繪制一張圖片和如何把圖片顯示到3D物體上并進(jìn)行三維變換,這次介紹如何用Metal渲染攝像頭采集到的圖像。

Metal系列教程的代碼地址
OpenGL ES系列教程在這里;

你的star和fork是我的源動(dòng)力,你的意見能讓我走得更遠(yuǎn)。

正文

核心思路

AVFoundation采集攝像頭數(shù)據(jù)得到CMSampleBufferRef,用CoreVideo提供的方法將圖像數(shù)據(jù)轉(zhuǎn)為Metal的紋理,再用MetalPerformanceShaders的高斯模糊濾鏡對圖像進(jìn)行處理,結(jié)果展示到屏幕上。

效果展示

123.gif

具體步驟

1、Metal相關(guān)設(shè)置
- (void)setupMetal {
    self.mtkView = [[MTKView alloc] initWithFrame:self.view.bounds];
    self.mtkView.device = MTLCreateSystemDefaultDevice();
    [self.view insertSubview:self.mtkView atIndex:0];
    self.mtkView.delegate = self;
    self.mtkView.framebufferOnly = NO;
    self.commandQueue = [self.mtkView.device newCommandQueue];
    CVMetalTextureCacheCreate(NULL, NULL, self.mtkView.device, NULL, &_textureCache);
}

除了正常創(chuàng)建和初始化MTKView之外,這里還多兩行代碼:

  • 設(shè)置MTKView的dramwable紋理是可讀寫的;(默認(rèn)是只讀)
  • 創(chuàng)建CVMetalTextureCacheRef _textureCache,這是Core Video的Metal紋理緩存;
2、攝像頭采集設(shè)置
- (void)setupCaptureSession {
    self.mCaptureSession = [[AVCaptureSession alloc] init];
    self.mCaptureSession.sessionPreset = AVCaptureSessionPreset1920x1080;
    self.mProcessQueue = dispatch_queue_create("mProcessQueue", DISPATCH_QUEUE_SERIAL); // 串行隊(duì)列
    AVCaptureDevice *inputCamera = nil;
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) {
        if ([device position] == AVCaptureDevicePositionBack) {
            inputCamera = device;
        }
    }
    self.mCaptureDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:inputCamera error:nil];
    if ([self.mCaptureSession canAddInput:self.mCaptureDeviceInput]) {
        [self.mCaptureSession addInput:self.mCaptureDeviceInput];
    }
    self.mCaptureDeviceOutput = [[AVCaptureVideoDataOutput alloc] init];
    [self.mCaptureDeviceOutput setAlwaysDiscardsLateVideoFrames:NO];
    // 這里設(shè)置格式為BGRA,而不用YUV的顏色空間,避免使用Shader轉(zhuǎn)換
    [self.mCaptureDeviceOutput setVideoSettings:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]];
    [self.mCaptureDeviceOutput setSampleBufferDelegate:self queue:self.mProcessQueue];
    if ([self.mCaptureSession canAddOutput:self.mCaptureDeviceOutput]) {
        [self.mCaptureSession addOutput:self.mCaptureDeviceOutput];
    }
    AVCaptureConnection *connection = [self.mCaptureDeviceOutput connectionWithMediaType:AVMediaTypeVideo];
    [connection setVideoOrientation:AVCaptureVideoOrientationPortrait]; // 設(shè)置方向
    [self.mCaptureSession startRunning];
}

創(chuàng)建AVCaptureSessionAVCaptureDeviceInputAVCaptureVideoDataOutput,注意在創(chuàng)建AVCaptureVideoDataOutput時(shí),需要指定內(nèi)容格式,這里使用的是BGRA的格式;
同時(shí)需要設(shè)定采集的方向,否則圖像會(huì)出現(xiàn)旋轉(zhuǎn);

3、攝像頭采集回調(diào)
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
    CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    
    size_t width = CVPixelBufferGetWidth(pixelBuffer);
    size_t height = CVPixelBufferGetHeight(pixelBuffer);
    
    CVMetalTextureRef tmpTexture = NULL;
    // 如果MTLPixelFormatBGRA8Unorm和攝像頭采集時(shí)設(shè)置的顏色格式不一致,則會(huì)出現(xiàn)圖像異常的情況;
    CVReturn status = CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, self.textureCache, pixelBuffer, NULL, MTLPixelFormatBGRA8Unorm, width, height, 0, &tmpTexture);
    if(status == kCVReturnSuccess)
    {
        self.mtkView.drawableSize = CGSizeMake(width, height);
        self.texture = CVMetalTextureGetTexture(tmpTexture);
        CFRelease(tmpTexture);
    }
}

這是demo的核心內(nèi)容,攝像頭回傳CMSampleBufferRef數(shù)據(jù),找到CVPixelBufferRef,用CVMetalTextureCacheCreateTextureFromImage創(chuàng)建CoreVideo的Metal紋理緩存CVMetalTextureRef,最后通過CVMetalTextureGetTexture得到Metal的紋理;
這個(gè)過程與Metal入門教程(一)圖片繪制使用device newTextureWithDescriptor創(chuàng)建紋理,再通過texture replaceRegion的方式上傳紋理數(shù)據(jù)類似,但是性能上有提升。

4、渲染處理
- (void)drawInMTKView:(MTKView *)view {
    if (self.texture) {
        id<MTLCommandBuffer> commandBuffer = [self.commandQueue commandBuffer]; // 創(chuàng)建指令緩沖
        id<MTLTexture> drawingTexture = view.currentDrawable.texture; // 把MKTView作為目標(biāo)紋理
        
        MPSImageGaussianBlur *filter = [[MPSImageGaussianBlur alloc] initWithDevice:self.mtkView.device sigma:1]; // 這里的sigma值可以修改,sigma值越高圖像越模糊
        [filter encodeToCommandBuffer:commandBuffer sourceTexture:self.texture destinationTexture:drawingTexture]; // 把攝像頭返回圖像數(shù)據(jù)的原始數(shù)據(jù)
        
        [commandBuffer presentDrawable:view.currentDrawable]; // 展示數(shù)據(jù)
        [commandBuffer commit];
        
        self.texture = NULL;
    }
}

這也是demo的核心內(nèi)容,MetalPerformanceShaders是Metal的一個(gè)集成庫,有一些濾鏡處理的Metal實(shí)現(xiàn),demo選用其中的高斯模糊處理MPSImageGaussianBlur;
MPSImageGaussianBlur以一個(gè)Metal紋理作為輸入,以一個(gè)Metal紋理作為輸出;
這里的輸入是從攝像頭采集的圖像,也即是第三步創(chuàng)建的紋理;輸出的紋理是MTKViewcurrentDrawable.texture
在繪制完之后調(diào)用presentDrawable:展示渲染結(jié)果。

注意事項(xiàng)

1、運(yùn)行后Crash,提示frameBufferOnly texture not supported for compute
這是因?yàn)?code>MTKView的drawable紋理默認(rèn)是只用來展示渲染結(jié)果,只允許作為framebuffer attachments,需要設(shè)置framebufferOnly為NO;

self.mtkView.framebufferOnly = NO;

2、圖像顯示異常,偏綠or偏藍(lán)
如果MTLPixelFormatBGRA8Unorm和攝像頭采集時(shí)設(shè)置的顏色格式不一致,則會(huì)出現(xiàn)圖像異常的情況,以下兩行代碼需要設(shè)置同樣的格式:

    [self.mCaptureDeviceOutput setVideoSettings:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]];

    CVReturn status = CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, self.textureCache, pixelBuffer, NULL, MTLPixelFormatBGRA8Unorm, width, height, 0, &tmpTexture);

3、圖像顯示異常,倒置or旋轉(zhuǎn)
如果出現(xiàn)圖像朝向異常的情況,可以通過下面的兩種方式進(jìn)行修改:

  • 修改AVCaptureConnection的朝向:
    [connection setVideoOrientation:AVCaptureVideoOrientationPortrait];
  • 或者給MTKView增加旋轉(zhuǎn)變換:
    self.mtkView.transform = CGAffineTransformMakeRotation(M_PI / 2);

總結(jié)

本文有兩個(gè)核心點(diǎn):CVPixelBufferRef創(chuàng)建Metal紋理以及MetalPerformanceShaders的使用和理解,這兩個(gè)點(diǎn)也引入后續(xù)Metal更復(fù)雜的能力,分別是視頻渲染和自定義Shader計(jì)算。
同時(shí)從這個(gè)demo可以看到相對OpenGL,Metal對圖像的處理更為方便,代碼也更為精簡。
代碼的地址在這里,歡迎交流。

好玩的Metal
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容