LoginSignup
2
2

More than 5 years have passed since last update.

32bit float/16bit short表現のグレースケール画像を CGImage化する

Last updated at Posted at 2014-11-09

OpenCVなどで様々な実験をしていると、32bit float/16bit shortで表現された画像を扱う機会も多くなりますね。
これをcv::imageShow()などを使わずに、Cocoaネイティブで扱いたい時のテクニックです。最後にはNSImageのインスタンスを作成するので、これをNSImageViewなどに貼ればOK。

32bit float

void *imageData = xxx;  //32bit float 表現のイメージバイト列
size_t width = xxx;     //イメージ幅
size_t height = xxx;    //イメージ高さ

NSColorSpace *cs = [NSColorSpace genericGrayColorSpace];
CGContextRef context = CGBitmapContextCreate(imageData, width, height, 8 * sizeof(float), width * sizeof(float), cs.CGColorSpace, kCGBitmapByteOrder32Host|kCGBitmapFloatComponents|kCGImageAlphaNone);
CGImageRef image = CGBitmapContextCreateImage(context);
NSImage *nsImage = [[NSImage alloc] initWithCGImage:image size:NSZeroSize];
CGContextRelease(context);
CGImageRelease(image);

16bit short

同様に、16bit shortで表現された画像も扱うことができます。
ほとんど32bit floatの時と同じで、ちょっと引数が違うだけです。

void *imageData = xxx;  //16bit float 表現のイメージバイト列
size_t width = xxx;     //イメージ幅
size_t height = xxx;    //イメージ高さ

NSColorSpace *cs = [NSColorSpace genericGrayColorSpace];
CGContextRef context = CGBitmapContextCreate(imageData, width, height, 8 * sizeof(short), width * sizeof(short), cs.CGColorSpace, kCGBitmapByteOrder16Host|kCGImageAlphaNone);
CGImageRef image = CGBitmapContextCreateImage(context);
NSImage *nsImage = [[NSImage alloc] initWithCGImage:image size:NSZeroSize];
CGContextRelease(context);
CGImageRelease(image);
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2