ios - 该算法如何计算 rgb 颜色?

标签 ios objective-c avfoundation

这是我的代码:

- (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] 范围内的 float 。捕获的图像具有 [0, 255] 范围内的整数颜色值。

算法会计算平均值。首先,它会将图像的所有颜色值相加,即总共 height x width 样本。因此,聚合值必须除以 height x width(样本数)和 255(将其从 [0, 255] 转换为 [0, 1] 范围)。

关于ios - 该算法如何计算 rgb 颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41509725/

相关文章:

iphone - 设备中未播放警告声音?

ios - 如何使用SearchBar从服务器获取数据

ios - 添加两张图像并制作一张

ios - 访问在几个不同的可能类中设置的 BOOL 标志

php - 使用 iOS 模拟器进行简单的文本检索

swift - 使用 Apple 的 AVFoundationExporter 示例代码将 AIFF 导出到 AAC 让我有些问题

Objective-C - NSXML 读取我不会读取的新行

ios - UIButton 标题文本颜色

ios - 无法设置不同的视频时长以在iOS中捕获和编辑视频

ios - iOS中的视频重叠