ncnn::Mat转iOS CVPixelBufferRef
2018-05-11 本文已影响351人
陆号
基本思路:mat转rgba,转CGImageRef,再转到PixelBuffer
static void to_argb(const ncnn::Mat& m, u_int8_t* argb)
{
const float* ptr0 = m.channel(0);
const float* ptr1 = m.channel(1);
const float* ptr2 = m.channel(2);
#define SATURATE_CAST_UCHAR(X) (u_int8_t)::std::min(::std::max((int)(X), 0), 255);
int size = m.w * m.h;
int remain = size;
for (; remain>0; remain--)
{
argb[3]=255;
argb[0] = SATURATE_CAST_UCHAR(*ptr0);//r
argb[1] = SATURATE_CAST_UCHAR(*ptr1);//g
argb[2] = SATURATE_CAST_UCHAR(*ptr2);//b
argb += 4;
ptr0++;
ptr1++;
ptr2++;
}
#undef SATURATE_CAST_UCHAR
}
CVPixelBufferRef copyDataFromMat(const ncnn::Mat& m)
{
u_int8_t *newBitmap = new u_int8_t[m.h*m.w*4];
to_argb(m, newBitmap);
//创建image
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
void *colorData = newBitmap;
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, colorData, m.h*4*m.w, NULL);
CGImageRef cgImage2 = CGImageCreate(m.w,
m.h,
8,
8 * 4,
m.w*4,
colorSpace,
kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault,
provider,
NULL,
NO,
kCGRenderingIntentDefault);
CGDataProviderRelease(provider);
UIImage *image = [UIImage imageWithCGImage:cgImage2];
//转为PixelBuffer
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
[NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey,
nil];
CVPixelBufferRef pxbuffer = NULL;
CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault,
m.w,
m.h,
kCVPixelFormatType_32ARGB,
(__bridge CFDictionaryRef) options,
&pxbuffer);
CVPixelBufferLockBaseAddress(pxbuffer, 0);
void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
CGContextRef context = CGBitmapContextCreate(pxdata,
m.w,
m.h,
8,
CVPixelBufferGetBytesPerRow(pxbuffer),
colorSpace,
(CGBitmapInfo)kCGImageAlphaNoneSkipFirst);
CGContextConcatCTM(context, CGAffineTransformIdentity);
CGContextDrawImage(context, CGRectMake(0,0,m.w,m.h),cgImage2);
CGContextRelease(context);
CGImageRelease(cgImage2);
CGColorSpaceRelease(colorSpace);
CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
delete[] newBitmap;
return pxbuffer;
}