hachzz
hachzz

Reputation: 11

How does this algorithm calculate rgb color?

Here is my code:

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

    // this is the image buffer
    CVImageBufferRef cvimgRef = CMSampleBufferGetImageBuffer(sampleBuffer);
    // Lock the image buffer
    CVPixelBufferLockBaseAddress(cvimgRef,0);
    // access the data
    size_t width=CVPixelBufferGetWidth(cvimgRef);
    size_t height=CVPixelBufferGetHeight(cvimgRef);
    // get the raw image bytes
    uint8_t *buf=(uint8_t *) CVPixelBufferGetBaseAddress(cvimgRef);
    size_t bprow=CVPixelBufferGetBytesPerRow(cvimgRef);
    // and pull out the average rgb value of the frame
    float r=0,g=0,b=0;
    int test = 0;
    for(int y=0; y<height; y++) {
        for(int x=0; x<width*4; x+=4) {
            b+=buf[x];
            g+=buf[x+1];
            r+=buf[x+2];
        }
        buf+=bprow;
        test += bprow;
    }
    r/=255*(float) (width*height);
    g/=255*(float) (width*height);
    b/=255*(float) (width*height);
    //Convert color to HSV
    RGBtoHSV(r, g, b, &h, &s, &v);
    // Do my stuff...

}

At last lines, after run: r, g, b have value between [0, 1]. But as I know, RGB have value from 0 to 255, isn't it?

I think last operations is get average value of r, g, b is that right? And why multipled by 255?

Upvotes: 0

Views: 182

Answers (1)

Codo
Codo

Reputation: 78825

The iOS classes CGColor and UIColor take colors as floating point numbers in the range [0, 1]. The captured images has integer color values in the range [0, 255].

The algorithm indead calculates the average. First it adds up all color values of the image, i.e. a total of height x width samples. So the aggregated values have to be devided by height x width (number of samples) and by 255 (to convert it from the [0, 255] to the [0, 1] range).

Upvotes: 2

Related Questions