NSImage to cv::Mat and vice versa

前端 未结 2 1924
夕颜
夕颜 2020-12-08 12:13

while working with OpenCV I need to convert a NSImage to an OpenCV multi-channel 2D matrix (cvMat) and vice versa.

What\'s the best way to do it?

Greets,

2条回答
  •  一生所求
    2020-12-08 12:57

    In -(id)initWithCVMat:(const cv::Mat&)cvMat, shouldn't you be adding the representation to self, rather than a new NSImage?

    -(id)initWithCVMat:(const cv::Mat *)iMat
    {
        if(self = [super init]) {
            NSData *tData = [NSData dataWithBytes:iMat->data length:iMat->elemSize() * iMat->total()];
    
            CGColorSpaceRef tColorSpace;
    
            if(iMat->elemSize() == 1) {
                tColorSpace = CGColorSpaceCreateDeviceGray();
            } else {
                tColorSpace = CGColorSpaceCreateDeviceRGB();
            }
    
            CGDataProviderRef tProvider = CGDataProviderCreateWithCFData((CFDataRef) tData);
    
            CGImageRef tImage = CGImageCreate(
                iMat->cols,
                iMat->rows,
                8,
                8 * iMat->elemSize(),
                iMat->step[0],
                tColorSpace,
                kCGImageAlphaNone | kCGBitmapByteOrderDefault,
                tProvider,
                NULL,
                false,
                kCGRenderingIntentDefault);
    
            NSBitmapImageRep *tBitmap = [[NSBitmapImageRep alloc] initWithCGImage:tImage];
            [self addRepresentation:tBitmap];
            [tBitmap release];
    
            CGImageRelease(tImage);
            CGDataProviderRelease(tProvider);
            CGColorSpaceRelease(tColorSpace);
        }
        return self;
    }
    

提交回复
热议问题