在iPhone上将内核数组转换为UIImage非常慢

时间:2011-09-16 12:55:55

标签: iphone image-processing filter

您好我有将图像过滤器内核数组转换为UIImage的代码。但iphone的执行速度非常慢?你有没有比这更好的代码?这是我的代码。

- (UIImage*) applyConvolve:(NSArray*)kernel
{
    CGImageRef inImage = self.CGImage;
    CFDataRef m_DataRef = CGDataProviderCopyData(CGImageGetDataProvider(inImage));  
    CFDataRef m_OutDataRef = CGDataProviderCopyData(CGImageGetDataProvider(inImage));  
    UInt8 * m_PixelBuf = (UInt8 *) CFDataGetBytePtr(m_DataRef);  
    UInt8 * m_OutPixelBuf = (UInt8 *) CFDataGetBytePtr(m_OutDataRef);  

    int h = CGImageGetHeight(inImage);
    int w = CGImageGetWidth(inImage);

    int kh = [kernel count] / 2;
    int kw = [[kernel objectAtIndex:0] count] / 2;
    int i = 0, j = 0, n = 0, m = 0;

    for (i = 0; i < h; i++) {
        for (j = 0; j < w; j++) {
            int outIndex = (i*w*4) + (j*4);
            double r = 0, g = 0, b = 0;
            for (n = -kh; n <= kh; n++) {
                for (m = -kw; m <= kw; m++) {
                    if (i + n >= 0 && i + n < h) {
                        if (j + m >= 0 && j + m < w) {
                            double f = [[[kernel objectAtIndex:(n + kh)] objectAtIndex:(m + kw)] doubleValue];
                            if (f == 0) {continue;}
                            int inIndex = ((i+n)*w*4) + ((j+m)*4);
                            r += m_PixelBuf[inIndex] * f;
                            g += m_PixelBuf[inIndex + 1] * f;
                            b += m_PixelBuf[inIndex + 2] * f;
                        }
                    }
                }
            }
            m_OutPixelBuf[outIndex]     = SAFECOLOR((int)r);
            m_OutPixelBuf[outIndex + 1] = SAFECOLOR((int)g);
            m_OutPixelBuf[outIndex + 2] = SAFECOLOR((int)b);
            m_OutPixelBuf[outIndex + 3] = 255;
        }
    }

    CGContextRef ctx = CGBitmapContextCreate(m_OutPixelBuf,  
                                             CGImageGetWidth(inImage),  
                                             CGImageGetHeight(inImage),  
                                             CGImageGetBitsPerComponent(inImage),
                                             CGImageGetBytesPerRow(inImage),  
                                             CGImageGetColorSpace(inImage),  
                                             CGImageGetBitmapInfo(inImage) 
                                             ); 

    CGImageRef imageRef = CGBitmapContextCreateImage(ctx);  
    CGContextRelease(ctx);
    UIImage *finalImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    CFRelease(m_DataRef);
    CFRelease(m_OutDataRef);
    return finalImage;

}

2 个答案:

答案 0 :(得分:0)

在iOS4中修复这个很有挑战性。如果您能够等待几个月,请在预发布文档中搜索“CIFilter”,看看会发生什么。

另请查看Jeff Lamarche's work in this area,虽然它没有完全出炉。

答案 1 :(得分:0)

iOS 5将Core Image带入iPhone / iPad(见http://developer.apple.com/technologies/ios5/)。一旦它可用,您可能会拥有所需的功能。您可以阅读Core Image here