很久以前,我一直在嘗試做同樣的事情,只使用Core Graphics,它可以完成,但相信我,效果並不像用戶期望的那樣流暢和柔和。所以,我知道如何與OpenCV合作,(開放計算機視覺庫),並且由於它是用C編寫的,我知道我可以在iPhone上使用它。 做你想用OpenCV做什麼是非常容易的。 首先,你需要一些函數來將UIImage轉換爲IplImage,這是OpenCV用來表示各種圖像的類型,反之亦然。
+ (IplImage *)CreateIplImageFromUIImage:(UIImage *)image {
CGImageRef imageRef = image.CGImage;
//This is the function you use to convert a UIImage -> IplImage
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
IplImage *iplimage = cvCreateImage(cvSize(image.size.width, image.size.height), IPL_DEPTH_8U, 4);
CGContextRef contextRef = CGBitmapContextCreate(iplimage->imageData, iplimage->width, iplimage->height,
iplimage->depth, iplimage->widthStep,
colorSpace, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault);
CGContextDrawImage(contextRef, CGRectMake(0, 0, image.size.width, image.size.height), imageRef);
CGContextRelease(contextRef);
CGColorSpaceRelease(colorSpace);
return iplimage;}
+ (UIImage *)UIImageFromIplImage:(IplImage *)image {
//Convert a IplImage -> UIImage
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSData * data = [[NSData alloc] initWithBytes:image->imageData length:image->imageSize];
//NSData *data = [NSData dataWithBytes:image->imageData length:image->imageSize];
CGDataProviderRef provider = CGDataProviderCreateWithCFData((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 alloc] initWithCGImage:imageRef];
CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpace);
[data release];
return ret;}
現在你有兩個你需要,你可以做任何你想要與你的IplImage的基本功能: 這是你想要的東西:
+(UIImage *)erasePointinUIImage:(IplImage *)image :(CGPoint)point :(int)r{
//r is the radious of the erasing
int a = point.x;
int b = point.y;
int position;
int minX,minY,maxX,maxY;
minX = (a-r>0)?a-r:0;
minY = (b-r>0)?b-r:0;
maxX = ((a+r) < (image->width))? a+r : (image->width);
maxY = ((b+r) < (image->height))? b+r : (image->height);
for (int i = minX; i < maxX ; i++)
{
for(int j=minY; j<maxY;j++)
{
position = ((j-b)*(j-b))+((i-a)*(i-a));
if (position <= r*r)
{
uchar* ptr =(uchar*)(image->imageData) + (j*image->widthStep + i*image->nChannels);
ptr[1] = ptr[2] = ptr[3] = ptr[4] = 0;
}
}
}
UIImage * res = [self UIImageFromIplImage:image];
return res;}
很抱歉的格式。
如果你想知道如何移植的OpenCV的iPhone Yoshimasa Niwa's
如果你想看看目前與OpenCV的工作在AppStore上的應用程序去獲得:Flags&Faces
感謝您指出我在正確的方向。我之前正在研究這個問題,但是找不到正確的方法來創建一個ARGB位圖(它看起來總是一個RGB),並且2)一旦我有二維像素數據數組,就可以操縱像素的alpha值。我會繼續挖掘併發布我發現的內容。謝謝。 – Joel 2010-06-05 14:52:24
如果您發佈瞭解決方案Joel,這將會非常方便。 (或者至少是相關的drawRect方法。) – livingtech 2010-12-09 23:50:13