Ios 该算法如何计算rgb颜色?

Ios 该算法如何计算rgb颜色?,ios,objective-c,avfoundation,Ios,Objective C,Avfoundation,这是我的密码: - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection { // this is the image buffer CVImageBufferRef cvimgRef = CMSampleBufferGet

这是我的密码:

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

}
-(void)captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)SampleBufferfromConnection:(AVCaptureConnection*)连接{
//这是图像缓冲区
CVImageBufferRef cvimgRef=CMSampleBufferGetImageBuffer(sampleBuffer);
//锁定图像缓冲区
CVPixelBufferLockBaseAddress(cvimgRef,0);
//访问数据
size\u t width=CVPixelBufferGetWidth(cvimgRef);
尺寸高度=CVPixelBufferGetHeight(cvimgRef);
//获取原始图像字节数
uint8_t*buf=(uint8_t*)CVPixelBufferGetBaseAddress(cvimgRef);
size_t bprow=CVPixelBufferGetBytesPerRow(cvimgRef);
//并拉出帧的平均rgb值
浮点数r=0,g=0,b=0;
int检验=0;

对于(int y=0;yiOS类
CGColor
UIColor
将颜色作为[0,1]范围内的浮点数。捕获的图像具有[0,255]范围内的整数值


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

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


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

谢谢。但我不明白为什么要将其转换为[0,1]范围?为什么不用高度*宽度来划分?(如果r/=(浮动)(宽度*高度),r将大于255)。我更新了我的代码。ty!它们被转换为0-1范围,因为
RGBtoHSV
方法希望RGB值在0-1范围内,而不是0-255范围内,就像
UIColor
方法一样。@hachzz别忘了接受解决问题的答案。这表明你的问题得到了回答,并且给了你更多的声誉。谢谢。但我不明白为什么要将其转换为[0,1]范围?为什么不直接用高度*宽度除以?(如果r/=(float)(宽度*高度),r将大于255)。我更新了我的代码。ty!它们被转换为0-1范围,因为
RGBtoHSV
方法希望RGB值在0-1范围内,而不是0-255范围内,就像
UIColor
方法一样。@hachzz别忘了接受解决问题的答案。这表明你的问题得到了回答,并且给了你更多的声誉.