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);