我正在开发一个 ios 应用程序,它使用一些 opencv 功能(删除背景、边缘检测等)
除其他外,我加载透明图像(png)。由于某种原因,当我加载图像时,opencv 决定忽略一些透明区域,同时尊重其他区域。我可以通过将我的半透明 UIImage 转换为 IplImage 然后返回 UIImage(不对 iplimage 进行任何操作)并将两个图像保存到本地文件来看到这一点。
这是我用于将 UIImage 转换为 IplImage 并向后转换的代码:
- (IplImage *)CreateIplImageFromUIImageWithTransparency:(UIImage *)image {
// Getting CGImage from UIImage
CGImageRef imageRef = image.CGImage;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// Creating temporal IplImage for drawing
IplImage *iplimage = cvCreateImage(
cvSize(image.size.width,image.size.height), IPL_DEPTH_8U, 4
);
// Creating CGContext for temporal IplImage
CGContextRef contextRef = CGBitmapContextCreate(
iplimage->imageData, iplimage->width, iplimage->height,
iplimage->depth, iplimage->widthStep,
colorSpace, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault
);
// Drawing CGImage to CGContext
CGContextDrawImage(
contextRef,
CGRectMake(0, 0, image.size.width, image.size.height),
imageRef
);
CGContextRelease(contextRef);
CGColorSpaceRelease(colorSpace);
// Creating result IplImage
IplImage *ret = cvCreateImage(cvGetSize(iplimage), IPL_DEPTH_8U, 4);
cvCvtColor(iplimage, ret, CV_RGBA2BGRA);
cvReleaseImage(&iplimage);
return ret;
}
- (UIImage *)UIImageFromIplImage:(IplImage *)image {
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, kCGBitmapByteOrderDefault | kCGImageAlphaLast ,
provider, NULL, false, kCGRenderingIntentDefault);
UIImage *ret = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpace);
return ret;
}
什么可能导致这种行为?
谢谢