如何更改结果以在Objective C中打印RGB像素值

时间:2017-02-23 01:25:04

标签: ios iphone

我有这个代码,我希望它返回每个像素的RGB颜色值,而不是亮度。目前它将每个像素的亮度打印到命令行上,我想要改变它以打印每个像素的RGB值。我是Objective-C的新手,所以非常感谢一些帮助和解释:)。

An example of what I have so far. This image shows the brightness of each pixel

 // 1. Get pixels of image
  CGImageRef inputCGImage = [image CGImage];
  NSUInteger width = CGImageGetWidth(inputCGImage);
  NSUInteger height = CGImageGetHeight(inputCGImage);

  NSUInteger bytesPerPixel = 4;
  NSUInteger bytesPerRow = bytesPerPixel * width;
  NSUInteger bitsPerComponent = 8;

  UInt32 * pixels;
  pixels = (UInt32 *) calloc(height * width, sizeof(UInt32));

  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  CGContextRef context = CGBitmapContextCreate(pixels, width, height,
                                               bitsPerComponent, bytesPerRow, colorSpace,
                                               kCGImageAlphaPremultipliedLast|kCGBitmapByteOrder32Big);

  CGContextDrawImage(context, CGRectMake(0, 0, width, height), inputCGImage);

  CGColorSpaceRelease(colorSpace);
  CGContextRelease(context);

#define Mask8(x) ( (x) & 0xFF )
#define R(x) ( Mask8(x) )
#define G(x) ( Mask8(x >> 8 ) )
#define B(x) ( Mask8(x >> 16) )

  // 2. Iterate and log!
  NSLog(@"Brightness of image:");
  UInt32 * currentPixel = pixels;
  for (NSUInteger j = 0; j < height; j++) {
    for (NSUInteger i = 0; i < width; i++) {
      UInt32 color = *currentPixel;

      printf("%3.0f ", (R(color)+G(color)+B(color))/3.0);
      currentPixel++;
    }
    printf("\n");
  }

  free(pixels);

1 个答案:

答案 0 :(得分:0)

只需更改此行:

printf("%3.0f ", (R(color)+G(color)+B(color))/3.0);

printf("(r=%3.0f, g=%3.0f, b=%3.0f) ", R(color), G(color), B(color));