如何遍历UIImage的所有像素?

时间:2013-03-14 16:00:46

标签: cocoa core-graphics

Hey Guys我目前正在尝试迭代UIImage的所有像素,但是我实现它的方式需要花费太多时间。所以我认为这是我实施它的错误方式。 这是我如何获得像素的RGBA值的方法:

+(NSArray*)getRGBAsFromImage:(UIImage*)image atX:(int)xx andY:(int)yy count:(int)count
{
    // Initializing the result array
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:count];

    // First get the image into your data buffer
    CGImageRef imageRef = [image CGImage];                      // creating an Instance of
    NSUInteger width = CGImageGetWidth(imageRef);               // Get width of our Image
    NSUInteger height = CGImageGetHeight(imageRef);             // Get height of our Image
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); // creating our colour Space

    // Getting that raw Data out of an image
    unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));


    NSUInteger bytesPerPixel = 4;                               // Bytes per pixel defined
    NSUInteger bytesPerRow = bytesPerPixel * width;             // Bytes per row
    NSUInteger bitsPerComponent = 8;                            // Bytes per component

    CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace); // releasing the color space

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);

    // Now your rawData contains the image data in the RGBA8888 pixel format.
    int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
    for (int ii = 0 ; ii < count ; ++ii)
    {
        CGFloat red   = (rawData[byteIndex]     * 1.0) / 255.0;
        CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0;
        CGFloat blue  = (rawData[byteIndex + 2] * 1.0) / 255.0;
        CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
        byteIndex += 4;

        UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
        [result addObject:acolor];
    }

    free(rawData);
    return result;
}

这是我解析所有像素的代码:

    for (NSUInteger y = 0 ; y < self.originalPictureWidth; y++) {
        for (NSUInteger x = 0 ; x < self.originalPictureHeight; x++) {
            NSArray * originalRGBA = [ComputerVisionHelperClass getRGBAsFromImage:self.originalPicture atX:(int)x andY:(int)y count:1];
            NSArray * referenceRGBA = [ComputerVisionHelperClass getRGBAsFromImage:self.referencePicture atX:(int)referenceIndexX andY:(int)referenceIndexY count:1];
// Do something else ....
        }
    }

是否有更快的方法来获取uiimage实例的所有RGBA值?

1 个答案:

答案 0 :(得分:1)

对于每个像素,您都会生成图像的新副本,然后将其丢弃。是的,只需获取一次数据然后处理该字节数组就会快得多。

但它在很大程度上取决于“做别的事”。有许多CoreImage和vImage函数可以非常快速地进行图像处理,但您可能需要以不同方式处理问题。这取决于你在做什么。