Return to Snippet

Revision: 29287
at July 25, 2010 17:38 by dio


Initial Code
/* IplImage to NSImage
  * Kelly Breed
*/
#import <Cocoa/Cocoa.h>
#include "NSutilities.h"
#include "cxcore.h"
#include "highgui.h"
#include "cv.h"

NSImage* opencvImageToNSImage(IplImage *img){
	char *d = img->imageData; // Get a pointer to the IplImage image data.
	
	NSString *COLORSPACE;
	if(img->nChannels == 1){
		COLORSPACE = NSDeviceWhiteColorSpace;
	}
	else{
		COLORSPACE = NSDeviceRGBColorSpace;
	}
	
	NSBitmapImageRep *bmp = [[NSBitmapImageRep alloc]  
initWithBitmapDataPlanes:NULL pixelsWide:img->width pixelsHigh:img- 
 >height bitsPerSample:img->depth samplesPerPixel:img->nChannels  
hasAlpha:NO isPlanar:NO colorSpaceName:COLORSPACE bytesPerRow:img- 
 >widthStep bitsPerPixel: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; y<img->height; y++){
		for(x=0; x<img->width; 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];
			}
			else{
				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 alloc] initWithData:tif];
	
	return [im autorelease];
}

Initial URL
http://bit.ly/9RlIHT

Initial Description


Initial Title
IplImage to NSImage

Initial Tags


Initial Language
Objective C