我正在使用这个。我的cv:Mat
被配置为BGR(8UC3)颜色格式。
CVImageBufferRef -> cv::Mat
- (cv::Mat) matFromImageBuffer: (CVImageBufferRef) buffer {
cv::Mat mat ;
CVPixelBufferLockBaseAddress(buffer, 0);
void *address = CVPixelBufferGetBaseAddress(buffer);
int width = (int) CVPixelBufferGetWidth(buffer);
int height = (int) CVPixelBufferGetHeight(buffer);
mat = cv::Mat(height, width, CV_8UC4, address, 0);
CVPixelBufferUnlockBaseAddress(buffer, 0);
return mat;
}
将cv::Mat转换为CVImageBufferRef(CVPixelBufferRef)
- (CVImageBufferRef) getImageBufferFromMat: (cv::Mat) mat {
cv::cvtColor(mat, mat, CV_BGR2BGRA);
int width = mat.cols;
int height = mat.rows;
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:width], kCVPixelBufferWidthKey,
[NSNumber numberWithInt:height], kCVPixelBufferHeightKey,
nil];
CVPixelBufferRef imageBuffer;
CVReturn status = CVPixelBufferCreate(kCFAllocatorMalloc, width, height, kCVPixelFormatType_32BGRA, (CFDictionaryRef) CFBridgingRetain(options), &imageBuffer) ;
NSParameterAssert(status == kCVReturnSuccess && imageBuffer != NULL);
CVPixelBufferLockBaseAddress(imageBuffer, 0);
void *base = CVPixelBufferGetBaseAddress(imageBuffer) ;
memcpy(base, mat.data, _mat.total()*4);
CVPixelBufferUnlockBaseAddress(imageBuffer, 0);
return imageBuffer;
}
cv::Mat mat(height, width, CV_8UC1, baseaddress, CVPixelBufferGetBytesPerRow(buffer));
此外,这个答案假设相机的videoSettings正在使用其中一个kCMPixelFormat_422YpCbCr8
CMPixelFormatTypes。 - Drew H