iPhone中的图像直方图

时间:2011-08-09 02:52:13

标签: iphone objective-c image-processing histogram

我正在寻找一种在iPhone上获取图像直方图的方法。 OpenCV库太大了,无法包含在我的应用程序中(OpenCV大约70MB编译),但我可以使用OpenGL。但是,我不知道如何做其中任何一个。

我已经找到了如何获取图像的像素,但无法形成直方图。这似乎应该很简单,但我不知道如何将 uint8_t 存储到数组中。

以下是查找像素的相关问题/答案:

Getting RGB pixel data from CGImage

2 个答案:

答案 0 :(得分:0)

uint8_t *只是一个指向包含给定颜色字节的c数组的指针,即{r,g,b,a}或者图像缓冲区的颜色字节布局。

因此,请参考您提供的链接以及直方图的定义:

//Say we're in the inner loop and we have a given pixel in rgba format
const uint8_t* pixel = &bytes[row * bpr + col * bytes_per_pixel];
//Now save to histogram_counts uint32_t[4] planes r,g,b,a
//or you could just do one for brightness
//If you want to do data besides rgba, use bytes_per_pixel instead of 4
for (int i=0; i<4; i++) {
    //Increment count of pixels with this value
    histogram_counts[i][pixel[i]]++;
}

答案 1 :(得分:0)

您可以使用CGRef拍摄图像的RGB颜色。请看下面我使用的方法。

- (UIImage *)processUsingPixels:(UIImage*)inputImage {

// 1. Get the raw pixels of the image
UInt32 * inputPixels;

CGImageRef inputCGImage = [inputImage CGImage];
NSUInteger inputWidth = CGImageGetWidth(inputCGImage);
NSUInteger inputHeight = CGImageGetHeight(inputCGImage);

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

NSUInteger bytesPerPixel = 4;
NSUInteger bitsPerComponent = 8;

NSUInteger inputBytesPerRow = bytesPerPixel * inputWidth;

inputPixels = (UInt32 *)calloc(inputHeight * inputWidth, sizeof(UInt32));

CGContextRef context = CGBitmapContextCreate(inputPixels, inputWidth, inputHeight,
                                             bitsPerComponent, inputBytesPerRow, colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

// 3. Convert the image to Black & White
for (NSUInteger j = 0; j < inputHeight; j++) {
    for (NSUInteger i = 0; i < inputWidth; i++) {
        UInt32 * currentPixel = inputPixels + (j * inputWidth) + i;
        UInt32 color = *currentPixel;

        // Average of RGB = greyscale
        UInt32 averageColor = (R(color) + G(color) + B(color)) / 3.0;

        *currentPixel = RGBAMake(averageColor, averageColor, averageColor, A(color));
    }
}

// 4. Create a new UIImage
CGImageRef newCGImage = CGBitmapContextCreateImage(context);
UIImage * processedImage = [UIImage imageWithCGImage:newCGImage];

// 5. Cleanup!
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);

   return processedImage;
}