Thursday, November 11, 2010

Convert IplImage to NSImage in XCode

Convert IplImage to NSImage in XCode

After doing some searching around I ran across this piece of code.

/* IplImage to NSImage
 * Kelly Breed

NSImage* opencvImageToNSImage(IplImage *img){
char *d = img->imageData// Get a pointer to the IplImage image data.
if(img->nChannels == 1){
COLORSPACE = NSDeviceWhiteColorSpace;
NSBitmapImageRep *bmp = [[NSBitmapImageRep alloc]  
 initWithBitmapDataPlanes:NULL pixelsWide:img->width pixelsHigh:img->heightbitsPerSample:img->depth samplesPerPixel:img->nChannels  
 hasAlpha:NO isPlanar:NO colorSpaceName:COLORSPACE bytesPerRow:img->widthStepbitsPerPixel:0];
// Move the IplImage data into the NSBitmapImageRep. widthStep is used in the inner for loop due to the
//   difference between actual bytes in the former and pixel locations in the latter.
// Assignment to colors[] is reversed because that's how an IplImage stores the data.
int x, y;
unsigned int colors[3];
for(y=0; yheight; y++){
for(x=0; xwidth; x++){
if(img->nChannels > 1){
colors[2] = (unsigned int) d[(y * img->widthStep) + (x*3)]; // x*3 due to difference between pixel coords and actual byte layout.
colors[1] = (unsigned int) d[(y * img->widthStep) + (x*3)+1];
colors[0] = (unsigned int) d[(y * img->widthStep) + (x*3)+2];
colors[0] = (unsigned int)d[(y * img->width) + x];
//NSLog(@"colors[0] = %d", colors[0]);
[bmp setPixel:colors atX:x y:y];
NSData *tif = [bmp TIFFRepresentation];
NSImage *im = [[NSImage allocinitWithData:tif];
return [im autorelease];

It appears that it converts an IplImage to an NSImage. I got it from here. It seems like it's going to work, I'll post again in the next few days with an update. If it does work, I'll be able to write more GUI friendly based applications with openCV because I'll be able to use interface builder to build all of the GUI components.

No comments:

Post a Comment