问题描述
对于后代化算法,我需要对 std :: vector
中存在的颜色值( QRgb
)求平均值.
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?
推荐答案
由于 QRgb
只是ARGB格式的32位无符号整数,不足以添加颜色,这很可能导致溢出.但是 QColor
也不因为它使用定点16位整数作为颜色分量就足够了,因此也不能处理超出有效[0,1]范围的颜色.因此,您不能为此使用 QRgb
或 QColor
,因为它们会将每个部分和限制在有效范围内.由于它们的精度有限,您也无法在添加颜色之前预先对其进行颜色设置.
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();
这篇关于平均QRgb值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!