最近傍探索(Nearest Neighbor Search)法で画像をスケーリングするtemplate関数のサンプルコードを載せます。
最適化を試みましたが、結果的にコンパイラの自動最適化に速度が勝てなかったので、最適化前のコードを載せます。最も効率の良い書き方があるかもしれません。
引数
in_src: 元画像データの1次元配列
src_width: 元画像の横解像度
src_height: 元画像の縦解像度
num_channels: 画像のチャンネル数
o_dst: 出力画像データの1次元配列
dst_width: 出力画像の横解像度
dst_height: 出力画像の縦解像度
最適化を試みましたが、結果的にコンパイラの自動最適化に速度が勝てなかったので、最適化前のコードを載せます。最も効率の良い書き方があるかもしれません。
引数
in_src: 元画像データの1次元配列
src_width: 元画像の横解像度
src_height: 元画像の縦解像度
num_channels: 画像のチャンネル数
o_dst: 出力画像データの1次元配列
dst_width: 出力画像の横解像度
dst_height: 出力画像の縦解像度
template<typename T> void ScaleImageNearestNeighbor(
         const T *in_src, int src_width, int src_height, int num_channels,
                                                              T *o_dst,         int dst_width, int dst_height
){
         float scale_w = src_width/static_cast<float>(dst_width);
         float scale_h = src_height/static_cast<float>(dst_height);
         int dst_size = dst_width * dst_height * num_channels;
         int src_size = src_width * src_height * num_channels;
        
         {
                  int x, y, c, i_dst, i_src;
                  int yw_src, yw_dst;
                  //** unoptimized code ----------------------- 
                  for(y=0; y<dst_height; ++y){
                           yw_src = static_cast<int>(y*scale_h)*src_width;
                           yw_dst = y*dst_width;
                           for(x=0; x<dst_width; ++x){
                                    i_dst = (yw_dst + x) * num_channels;
                                    i_src = (yw_src + static_cast<int>(x*scale_w)) * num_channels;
                                    for(c=0; c<num_channels; ++c){
                                             o_dst[i_dst+c] = in_src[i_src+c];
                                    }
                           }
                  }
         }
}