关闭

UIImage与Iplimage相互转换

880人阅读 评论(0) 收藏 举报

UIImage与Iplimage相互转换

作者:知识天地  来源:博客园  发布时间:2012-02-27 15:43  阅读:48 次  原文链接   [收藏]  

原创文章,转载请注明出处:http://www.cnblogs.com/mfryf/archive/2012/02/27/2369952.html 

Opencv中所有的图像处理都是Iplimage类型的格式,iso的sdk显示一张图像的对象类型是UIImage。因此,我们如果想在ios环境中使用opencv,

就必须把UIImage转换成Iplimage,处理之后再把Iplimage转换成UIImage。非常幸运的是,IOS的sdk为我们提供了转换API。

从UIImage创建一个Iplimage结构,代码如下:

// NOTE you SHOULD cvReleaseImage() for the return value when end of the code.
- (IplImage *)CreateIplImageFromUIImage:(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, 3);
cvCvtColor(iplimage, ret, CV_RGBA2BGR);
cvReleaseImage(&iplimage);

return ret;
}

使用玩iplimage之后,别忘记释放内存。cvreleaseImage().

从iplimage创建一张UIImage

代码如下:

// NOTE You should convert color mode as RGB before passing to this function
- (UIImage *)UIImageFromIplImage:(IplImage *)image {
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// Allocating the buffer for CGImage
NSData *data =
[NSData dataWithBytes:image->imageData length:image->imageSize];
CGDataProviderRef provider =
CGDataProviderCreateWithCFData((CFDataRef)data);
// Creating CGImage from chunk of IplImage
CGImageRef imageRef = CGImageCreate(
image->width, image->height,
image->depth, image->depth * image->nChannels, image->widthStep,
colorSpace, kCGImageAlphaNone|kCGBitmapByteOrderDefault,
provider, NULL, false, kCGRenderingIntentDefault
);
// Getting UIImage from CGImage
UIImage *ret = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpace);
return ret;
}

尽情的在ios中使用opencv吧~

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1909929次
    • 积分:19944
    • 等级:
    • 排名:第425名
    • 原创:9篇
    • 转载:1263篇
    • 译文:24篇
    • 评论:26条
    最新评论