3

For a posterization algorithmn I'm going to need to average the color values (QRgb) present in my std::vector.

How would you suggest to do it? Sum the 3 components separately then average them? Otherwise?

Christian Rau
  • 45,360
  • 10
  • 108
  • 185
Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134

1 Answers1

4

Since QRgb is just a 32-bit unsigned int in ARGB format it doesn't suffice for adding colors, which will most likely result in overflow. But also QColor doesn't suffice as it uses fixed-point 16-bit integers for the color components and therefore also cannot cope with colors out of the valid [0,1] range. So you cannot use QRgb or QColor for this as they clamp each partial sum to the valid range. Neither can you predivide the colors before adding them because of their limited precision.

So your best bet would really just be to sum up the individual components using floating point numbers and then divide them by the vector size:

std::vector<QRgb> rgbValues;

float r = 0.0f, g = 0.0f, b = 0.0f, a = 0.0f;
for(std::vector<QRgb>::const_iterator iter=rgbValues.begin(); 
    iter!=rgbValues.end(); ++iter)
{
    QColor color(*iter);
    r += color.redF();
    g += color.greenF();
    b += color.blueF();
    a += color.alphaF();
}

float scale = 1.0f / float(rgbValues.size());
QRgb = QColor::fromRgbF(r*scale, g*scale, b*scale, a*scale).rgba(); 
Christian Rau
  • 45,360
  • 10
  • 108
  • 185