Posted By

dio on 07/25/10


Tagged

IplImage


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

umang_nine


IplImage to NSImage


 / Published in: Objective C
 

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

  1. /* IplImage to NSImage
  2.   * Kelly Breed
  3. */
  4. #import <Cocoa/Cocoa.h>
  5. #include "NSutilities.h"
  6. #include "cxcore.h"
  7. #include "highgui.h"
  8. #include "cv.h"
  9.  
  10. NSImage* opencvImageToNSImage(IplImage *img){
  11. char *d = img->imageData; // Get a pointer to the IplImage image data.
  12.  
  13. NSString *COLORSPACE;
  14. if(img->nChannels == 1){
  15. COLORSPACE = NSDeviceWhiteColorSpace;
  16. }
  17. else{
  18. COLORSPACE = NSDeviceRGBColorSpace;
  19. }
  20.  
  21. initWithBitmapDataPlanes:NULL pixelsWide:img->width pixelsHigh:img-
  22. >height bitsPerSample:img->depth samplesPerPixel:img->nChannels
  23. hasAlpha:NO isPlanar:NO colorSpaceName:COLORSPACE bytesPerRow:img-
  24. >widthStep bitsPerPixel:0];
  25.  
  26. // Move the IplImage data into the NSBitmapImageRep. widthStep is
  27. used in the inner for loop due to the
  28. // difference between actual bytes in the former and pixel
  29. locations in the latter.
  30. // Assignment to colors[] is reversed because that's how an IplImage
  31. stores the data.
  32. int x, y;
  33. unsigned int colors[3];
  34. for(y=0; y<img->height; y++){
  35. for(x=0; x<img->width; x++){
  36. if(img->nChannels > 1){
  37. colors[2] = (unsigned int) d[(y * img->widthStep) + (x*3)]; //
  38. x*3 due to difference between pixel coords and actual byte layout.
  39. colors[1] = (unsigned int) d[(y * img->widthStep) + (x*3)+1];
  40. colors[0] = (unsigned int) d[(y * img->widthStep) + (x*3)+2];
  41. }
  42. else{
  43. colors[0] = (unsigned int)d[(y * img->width) + x];
  44. //NSLog(@"colors[0] = %d", colors[0]);
  45. }
  46. [bmp setPixel:colors atX:x y:y];
  47. }
  48. }
  49.  
  50. NSData *tif = [bmp TIFFRepresentation];
  51. NSImage *im = [[NSImage alloc] initWithData:tif];
  52.  
  53. return [im autorelease];
  54. }

Report this snippet  

You need to login to post a comment.