0

嘿,伙计们,我目前正在尝试遍历 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 值?

4

1 回答 1

1

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

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

于 2013-03-14T16:08:25.533 回答