2

我将 opencv 与 Xcode 一起使用,我使用此方法将 IplImage 转换为 UIImage:

-(UIImage *)UIImageFromIplImage:(IplImage *)image {
NSLog(@"IplImage (%d, %d) %d bits by %d channels, %d bytes/row %s", image->width, image->height, image->depth, image->nChannels, image->widthStep, image->channelSeq);

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSData *data = [NSData dataWithBytes:image->imageData length:image->imageSize];
CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge  CFDataRef)data);
CGImageRef imageRef = CGImageCreate(image->width, image->height,
                         image->depth, image->depth * image->nChannels, image->widthStep,
colorSpace, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault,
provider, NULL, false, kCGRenderingIntentDefault);
UIImage *ret = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:UIImageOrientationUp];
CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpace);
return ret;
}

问题是,当我将任何图像传递给此方法(png、jpg、tiff)时,会出现此错误:CGImageCreate: invalid image bits/pixel: 8,请帮助我解决该错误,谢谢。

4

2 回答 2

3

如果您的图像是灰色的(不是 RGBA),请使用:

colorSpace = CGColorSpaceCreateDeviceGray();

于 2013-06-06T09:25:40.183 回答
2

根据我在我的应用程序中所做的,您实际上需要在图像数据中提供一个 alpha 值。我所做的是将数据从 opencv 结构中取出,添加一个 alpha 值,然后创建 CGImage。这是我在 C++ API 中使用的代码(如果您坚持使用 C,只需将调用 aMat.ptr<>(y) 替换为指向第 y 行第一个像素的指针):

// Colorspace
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

 unsigned char* data = new unsigned char[4*aMat.cols*aMat.rows];
 for (int y = 0; y < aMat.rows; ++y)
 {
     cv::Vec3b *ptr = aMat.ptr<cv::Vec3b>(y);
     unsigned char *pdata = data + 4*y*aMat.cols;

     for (int x = 0; x < aMat.cols; ++x, ++ptr)
     {
         *pdata++ = (*ptr)[2];
         *pdata++ = (*ptr)[1];
         *pdata++ = (*ptr)[0];
         *pdata++ = 0;
     }
 }

 // Bitmap context
 CGContextRef context = CGBitmapContextCreate(data, aMat.cols, aMat.rows, 8, 4*aMat.cols, colorSpace, kCGImageAlphaNoneSkipLast);

 CGImageRef cgimage = CGBitmapContextCreateImage(context);

 CGColorSpaceRelease(colorSpace);
 CGContextRelease(context);
 delete[] data;

改组部分是必要的,因为 OpenCV 处理 BGR 图像,而 Quartz 需要 RGB。

于 2012-04-25T11:18:39.330 回答