This is not really a question but since I didn't find any information on such a transformation and because the transformation is not as trivial as it seems, I thought I'd post some code here.
The code is part of http://rubyk.org (BSD licence) so feel free to reuse.
Is there anything wrong with this code, or do you have a better alternative ?
cv::Mat cv::LoadImage(const char *path) {
ScopedPool pool;
NSURL *url = [NSURL fileURLWithPath:[[NSString stringWithUTF8String:path]
stringByExpandingTildeInPath]];
NSImage *image = [[NSImage alloc] initByReferencingURL:url];
if (!image) {
std::cerr << "Could not create image from path " << path << "\n";
// empty cv::Mat.
return cv::Mat();
}
[image autorelease];
NSSize size = [image size];
[image lockFocus];
NSBitmapImageRep *image_rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:
NSMakeRect(0, 0, size.width, size.height)];
[image unlockFocus];
if (!image_rep) {
std::cerr << "Could not get image data from path " << path << "\n";
// empty cv::Mat.
return cv::Mat();
}
[image_rep autorelease];
// bit depth
if ([image_rep bitsPerSample] != 8) {
std::cerr << "Unspupported image depth (" << [image_rep bitsPerSample] << ")\n";
return cv::Mat();
}
cv::Mat matrix(size.height, size.width, CV_MAKETYPE(CV_8U, [image_rep samplesPerPixel]), [image_rep bitmapData]);
// make sure Mat makes a copy of the data and starts managing it !
return matrix.clone();
}