Tuesday, October 25, 2011

Porting OpenCV 2.3.1 to iPhone 3GS/4/4S - 如何將OpenCV中影像處理輸出資料結構Mat的data轉出成為UIimage

透過OpenCV處理完的影像資料可以透過如下的程序轉回UIImage,就可以在iOS中任意顯示或儲存:
1. 先將OpenCV處理後在Mat資料結構中的RGB資料(result.data)轉成RGBA資料(img_data

    unsigned char * img_data = (unsigned char *)malloc(img_width * img_height * 4);

// Convert RGB data in Mat (result) to RGBA raw data buffer (img_data)
    for(i=0;i<img_height;i++){
        for(j=0;j<img_width;j++){
            img_data[i*img_width*4+j*4]=result.data[i*result.step[0]+j*3*2];
            img_data[i*img_width*4+j*4+1]=result.data[i*result.step[0]+j*3*2+2];
            img_data[i*img_width*4+j*4+2]=result.data[i*result.step[0]+j*3*2+4];
            img_data[i*img_width*4+j*4+3]=0xFF;
        }
    }


2. 透過如下的程序將RGBA資料(img_data)在轉成UIImage

    int bitsPerComponent = 8;
    int bitsPerPixel = 32;
    int bytesPerRow = 4 * img_width;
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, img_data, img_width*img_height*4, NULL);
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedFirst|kCGBitmapByteOrder32Little;
    CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
    CGImageRef imageRef = CGImageCreate(img_width, img_height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
    UIImage *myImage = [UIImage imageWithCGImage:imageRef];

No comments:

Post a Comment