I'm glad you managed with that
. Anyway I suggest you to use QT api, where it is possible to avoid code duplication.
And here's my suggestion of the second function. I suppose it's a bit more precise 
First of all, let me explain, why is it so. Pretend QRgb is a point with coordinates (r, g, b). Then imatge.colorTable() is a series of points you have to choose from, when approximating random QRgb.
Let's pretend you have to approximate point QRgb(R', G', B'). The best point to choose from imatge.colorTable() is the one, which is the most close to (R', G', B'). As you know, the distance betwean two points is calculated this way:
double distance(const QRgb &x, const QRgb &y)
{
int dRed = qRed(x) - qRed(y);
int dGreen = qGreen(x) - qGreen(y);
int dBlue = qBlue(x) - qBlue(y);
return sqrt(dRed * dRed + dGreen * dGreen + dBlue * dBlue);
}
double distance(const QRgb &x, const QRgb &y)
{
int dRed = qRed(x) - qRed(y);
int dGreen = qGreen(x) - qGreen(y);
int dBlue = qBlue(x) - qBlue(y);
return sqrt(dRed * dRed + dGreen * dGreen + dBlue * dBlue);
}
To copy to clipboard, switch view to plain text mode
Now your task is to find such an i, for which distance(color, imatge.colorTable()[i]) is the least. You present algorythm fits well
.
int FotoEditorFotos::obtenirIndexColor(const QRgb &colorRgb)
{
QVector<QRgb> taulaColor = imatge.colorTable();
/*
int indexRgb = taulaColor.indexOf(colorRgb);
if (indexRgb < 0)
{
*/
int indexRgb;
// Search for a similar color in the color table...
int n = taulaColor.count();
int verd = qGreen(colorRgb);
int vermell = qRed(colorRgb);
int blau = qBlue(colorRgb);
int alpha = qAlpha(colorRgb);
int diffMin = 3 * 255 * 255 + 1;
int diff;
QRgb rgb;
for (int i = 0; i < n; ++i)
{
rgb = taulaColor[i];
int dR = vermell - qRed(rgb);
int dG = verd - qGreen(rgb);
int dB = blau - qBlue(rgb);
diff = dR * dR + dG * dG + dB * dB;
if (diff < diffMin)
{
diffMin = diff;
indexRgb = i;
if (0 == diffMin) break;
}
}
// }
return indexRgb;
}
int FotoEditorFotos::obtenirIndexColor(const QRgb &colorRgb)
{
QVector<QRgb> taulaColor = imatge.colorTable();
/*
int indexRgb = taulaColor.indexOf(colorRgb);
if (indexRgb < 0)
{
*/
int indexRgb;
// Search for a similar color in the color table...
int n = taulaColor.count();
int verd = qGreen(colorRgb);
int vermell = qRed(colorRgb);
int blau = qBlue(colorRgb);
int alpha = qAlpha(colorRgb);
int diffMin = 3 * 255 * 255 + 1;
int diff;
QRgb rgb;
for (int i = 0; i < n; ++i)
{
rgb = taulaColor[i];
int dR = vermell - qRed(rgb);
int dG = verd - qGreen(rgb);
int dB = blau - qBlue(rgb);
diff = dR * dR + dG * dG + dB * dB;
if (diff < diffMin)
{
diffMin = diff;
indexRgb = i;
if (0 == diffMin) break;
}
}
// }
return indexRgb;
}
To copy to clipboard, switch view to plain text mode
Notes:
- For performance reasons it's better to compare squares of distances rather then distances themselves.
- There's no need to do indexRgb = taulaColor.indexOf(colorRgb)
Guess why.
Bookmarks