此算法如何计算 rgb 颜色



这是我的代码:

- (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...
}

在运行后的最后一行:r,g,b 的值介于 [0, 1] 之间。但据我所知,RGB 的值从 0 到 255,不是吗?

我认为最后的操作是获得 r、g、b 的平均值,对吗?为什么乘以 255?

iOS 类CGColorUIColor将颜色作为范围 [0, 1] 中的浮点数。捕获的图像具有 [0, 255] 范围内的整数颜色值。

算法 indead 计算平均值。首先,它将图像的所有颜色值相加,即高度 x 宽度样本的总和。因此,聚合值必须由高度 x 宽度(样本数)和 255(将其从 [0, 255] 转换为 [0, 1] 范围)来划分。

最新更新