First time here? Check out the FAQ!

Ask Your Question
2

Converting a Buffer to a Bitmap

asked Jul 31 '12

thomket gravatar image

updated Jul 31 '12

Hello together, I am relatively new to opencv and trying to use it in an iOs app. OpenCV will be used for other things, too, but the first thing I'm trying to do is to create a Bitmap-Image from a CVImageBufferRef. I'm doing it that way because I need image data without any compression if possible.

The data I'm getting should be uncompressed BGRA bytes so I'm using this function

cv::cvtColor(frame, frame, CV_BGRA2GRAY);

because I only need gray values and then I turn it into a NSData-Object and save it like this:

NSData *dataForRawBytes = [NSData dataWithBytes:frame.data length:frame.elemSize()*frame.total()];

[dataForRawBytes writeToFile:imageName atomically:YES];

The problem is that the data I'm getting out of this is not an image I can see, it's just symbols and stuff.

I would like to know if there are better ways to use openCV for this and is there a really good documentation for openCV especially in connection with iOs?

I'm grateful for every hint and help. Thanks!

Preview: (hide)

1 answer

Sort by » oldest newest most voted
0

answered Aug 6 '12

thomket gravatar image

updated Aug 22 '12

I found something! And I must say I was very blind.

CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
CVPixelBufferLockBaseAddress(imageBuffer,0);

size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);

cv::Mat frame(height, width, CV_8UC4, (void*)baseAddress);

CVPixelBufferUnlockBaseAddress(imageBuffer, 0);

cv::cvtColor(frame, frame, CV_BGRA2RGB);

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"ocv%d.BMP", picNum]];
const char* cPath = [filePath cStringUsingEncoding:NSMacOSRomanStringEncoding];

const cv::string newPaths = (const cv::string)cPath;

cv::imwrite(newPaths, frame);

I just have to use the imwrite function from opencv. This way I get BMP-files around 24 MB directly after the bayer-filter!

Preview: (hide)

Question Tools

Stats

Asked: Jul 31 '12

Seen: 2,572 times

Last updated: Aug 22 '12