私はイメージを持っています。すべてのピクセルにRGB強度に関する情報が含まれています。今私は、これらのチャンネルの強度を合計したいと思いますが、私はまたどのチャンネルの強度を合計するかを選択したいと思います。私は私ができる場合は、すべての条件を破棄したい画像における画素毎に、この関数を呼び出しますのでコンパイル時に関数を生成
int intensity(const unsiged char* pixel, bool red, bool green, bool blue){
return 0 + (red ? pixel[0] : 0) + (green ? pixel[1] : 0) + (blue ? pixel[2] : 0);
}
:このStraightforwad実装は次のようになります。今、私は任意の条件なしで画像ループや使用機能に入る前に、この発電機を使用することができます
std::function<int(const unsigned char* pixel)> generateIntensityAccumulator(
const bool& accumulateRChannel,
const bool& accumulateGChannel,
const bool& accumulateBChannel)
{
if (accumulateRChannel && accumulateGChannel && accumulateBChannel){
return [](const unsigned char* pixel){
return static_cast<int>(pixel[0]) + static_cast<int>(pixel[1]) + static_cast<int>(pixel[2]);
};
}
if (!accumulateRChannel && accumulateGChannel && accumulateBChannel){
return [](const unsigned char* pixel){
return static_cast<int>(pixel[1]) + static_cast<int>(pixel[2]);
};
}
if (!accumulateRChannel && !accumulateGChannel && accumulateBChannel){
return [](const unsigned char* pixel){
return static_cast<int>(pixel[2]);
};
}
if (!accumulateRChannel && !accumulateGChannel && !accumulateBChannel){
return [](const unsigned char* pixel){
return 0;
};
}
if (accumulateRChannel && !accumulateGChannel && !accumulateBChannel){
return [](const unsigned char* pixel){
return static_cast<int>(pixel[0]);
};
}
if (!accumulateRChannel && accumulateGChannel && !accumulateBChannel){
return [](const unsigned char* pixel){
return static_cast<int>(pixel[1]);
};
}
if (accumulateRChannel && !accumulateGChannel && accumulateBChannel){
return [](const unsigned char* pixel){
return static_cast<int>(pixel[0]) + static_cast<int>(pixel[2]);
};
}
if (accumulateRChannel && accumulateGChannel && !accumulateBChannel){
return [](const unsigned char* pixel){
return static_cast<int>(pixel[0]) + static_cast<int>(pixel[1]);
};
}
}
:だから私は、私はすべてのケースのための機能を持っている必要が推測
...
auto accumulator = generateIntensityAccumulator(true, false, true);
for(auto pixel : pixels){
auto intensity = accumulator(pixel);
}
...
しかし、それは多くのですこのような単純な作業のための書き込みをすることができます。私は、これを実現するためのより良い方法があると感じています。たとえば、コンパイラを使って私にとって汚い作業を行い、上記のすべてのケースを生成します。誰かが私を正しい方向に向けることができますか?
上記のパフォーマンスを実際にテストしましたか?プロセッサーは一般的に "前回と同じ結果"を仮定してブランチを最適化するので、ループ外で単純なブールテストを動かすことは大変重要であると私は驚いています... –
私は認めていません - パフォーマンスが向上します。私は支店の予感(http://igoro.com/archive/fast-and-slow-if-statements-branch-prediction-in-modern-processors/)について読んで、私のケースではうまくいくと思います。ありがとう! – Amadeusz
私は間違っている可能性があります...私はちょうど複雑すぎることをする前にパフォーマンステストを実行することを検討したいと思います。 –