2

I am using xcode and is currently trying to extract pixel values from the pixel buffer using the following code. However, when i print out the pixel values, it consists of negative values. Anyone has encountered such problem before?

part of the code is as below

- (void)captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer:
(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection
{

CVImageBufferRef Buffer = CMSampleBufferGetImageBuffer(sampleBuffer);

CVPixelBufferLockBaseAddress(Buffer, 0);
uint8_t* BaseAddress = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(Buffer, 0);
size_t Width = CVPixelBufferGetWidth(Buffer);
size_t Height = CVPixelBufferGetHeight(Buffer);
if (BaseAddress)
{
    IplImage* Temporary = cvCreateImage(cvSize(Width, Height), IPL_DEPTH_8U, 4);

    Temporary->imageData = (char*)BaseAddress;
    for (int i = 0; i < Temporary->width * Temporary->height; ++i) {
        NSLog(@"Pixel value: %d",Temporary->imageData[i]);
        //where i try to print the pixels
    }
}
Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
lkleung1
  • 57
  • 8
  • Please read about [this](http://stackoverflow.com/questions/28603693/how-can-retrieve-pixel-value-using-cvmat/), and especially my comments [here](http://stackoverflow.com/a/28739736/2436175) – Antonio Mar 04 '15 at 13:40

1 Answers1

1

The issue is that imageData of IplImage is a signed char. Thus, anything greater than 127 will appear as a negative number.

You can simply assign it to an unsigned char, and then print that, and you'll see values in the range between 0 and 255, like you probably anticipated:

for (int i = 0; i < Temporary->width * Temporary->height; ++i) {
    unsigned char c = Temporary->imageData[i];
    NSLog(@"Pixel value: %u", c);
}

Or you can print that in hex:

NSLog(@"Pixel value: %02x", c);
Rob
  • 415,655
  • 72
  • 787
  • 1,044