Skip to content

Instantly share code, notes, and snippets.

@jebai
Last active June 8, 2019 19:38
Show Gist options
  • Save jebai/8108287 to your computer and use it in GitHub Desktop.
Save jebai/8108287 to your computer and use it in GitHub Desktop.
- (void) parseBuffer:(CMSampleBufferRef) sampleBuffer
{
CVImageBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
CVPixelBufferLockBaseAddress( pixelBuffer, 0 );
//Processing here
int bufferWidth = CVPixelBufferGetWidth(pixelBuffer);
int bufferHeight = CVPixelBufferGetHeight(pixelBuffer);
unsigned char *pixel = (unsigned char *)CVPixelBufferGetBaseAddress(pixelBuffer);
// put buffer in open cv, no memory copied
cv::Mat mat = cv::Mat(bufferHeight,bufferWidth,CV_8UC4,pixel);
//End processing
CVPixelBufferUnlockBaseAddress( pixelBuffer, 0 );
}
@abram
Copy link

abram commented Jul 27, 2017

One suggestion, based on my experience using this: some iPhone device video streams have padding at the end of each pixelBuffer row, which will result in corrupted images if the Mat auto-calculates the step size. To fix it, manually set the 5th 'step' argument to cv::Mat to CVPixelBufferGetBytesPerRow(pixelBuffer). So line 14 would be:

cv::Mat mat = cv::Mat(bufferHeight,bufferWidth,CV_8UC4,pixel,CVPixelBufferGetBytesPerRow(pixelBuffer));

@mabounassif
Copy link

What encoding is this for? YUV?

@LiLejia
Copy link

LiLejia commented Jun 8, 2019

@mabounassif This piece expects RGB instead of YUV.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment