2013-08-27 140 views
0

在我的项目中,我需要显示给定图像的前三种颜色(请参见下面的示例图像)。功能要求是我必须单独获取图像中每个像素的前三种颜色,然后必须计算所有像素的颜色。最后,在给定图像中前三种呈现的颜色必须被列为输出。 (看看GPUImage,但我无法找到我的要求的任何代码)。谢谢..iOS:从图像的每个像素获取顶部颜色

enter image description here

+0

你正在寻找每个像素的颜色,或在现场发现的一般颜色? (例如,图像中有很多绿色,但实际上有很多不同的像素颜色彼此非常接近。) –

+0

寻找像素颜色RGB – Megan

+0

您的意思是,RGB颜色出现最多?如果是这样,我相信它可以完成,但可能需要几秒到几秒钟,这取决于图片上的像素数量。 –

回答

1

请尝试以下功能与双for循环。我想起了一些在这里发布的代码,然后做了一些修改。我不再开发iOS。所以我不能回答详细的问题。但是你应该能够从这个功能中得到一些想法。

- (UIColor *)getRGBAsFromImage:(UIImage *)image atX:(CGFloat)xx atY:(CGFloat)yy { 
    CGImageRef imageRef = [image CGImage]; 
    NSUInteger width = CGImageGetWidth(imageRef); 
    NSUInteger height = CGImageGetHeight(imageRef); 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
    unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char)); 
    NSUInteger bytesPerPixel = 4; 
    NSUInteger bytesPerRow = bytesPerPixel * width; 
    NSUInteger bitsPerComponent = 8; 
    CGContextRef context = CGBitmapContextCreate(rawData, width, height, 
              bitsPerComponent, bytesPerRow, colorSpace, 
                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); 
    CGColorSpaceRelease(colorSpace); 
    CGContextDrawImage(context, CGRectMake(0,0,width,height),imageRef); 
    CGContextRelease(context); 

    int index = 4*((width*yy)+xx); 
    int R = rawData[index]; 
    int G = rawData[index+1]; 
    int B = rawData[index+2]; 
    UIColor *aColor; 
    aColor = [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:1.0]; 
    rValue = R; gValue = G; bValue = B; 
    free(rawData); 
    return aColor; 
} 

//更新//

UIColor *c = [self getRGBAsFromImage:colorImage1.image atX:0 atY:0]; // colorImage1 is UIImageView 

获取图像的尺寸,第一。然后使用double for-loop迭代x和y值。然后将颜色值存储在您的目标数组中。

+0

很好,以及为什么值应该在参数中传递(atX:(CGFloat)xx atY:(CGFloat)yy)? – Megan

+0

我已经添加了进一步的解释。 –