2017-02-20 74 views
2

我正在寫一個金屬cnn代碼。 Metal提供MPSCNNLocalContrastNormalization, 由於實例規範化的概念稍有不同,因此我打算將它作爲內核函數來實現。我想實現實例規範化

但是,問題在於當從核函數中的輸入接收到的紋理中的特徵爲R,G,B時,應當獲得每個R,G,B的均值和方差。 我想知道如何實現這個。

enter image description here

kernel void instance_normalization_2darray(texture2d_array<float, access::sample> src [[ texture(0) ]], 
             texture2d_array<float, access::write> dst [[ texture(1) ]], 
             uint3 tid [[thread_position_in_grid]]) { 

} 


    kernel void calculate_avgA(texture2d_array<float, access::read> texture_in [[texture(0)]], 
          texture2d_array<float, access::write> texture_out [[texture(1)]], 
          uint3 tid [[thread_position_in_grid]]) 
{ 
    int width = texture_in.get_width(); 
    int height = texture_in.get_height(); 
    int depth = texture_in.get_array_size(); 
    float4 outColor; 


    uint3 kernelIndex(0,0,0); 
    uint3 textureIndex(0,0,0); 

    for(int k = 0; k < depth; k++) { 
     outColor = (0.0, 0.0, 0.0, 0.0); 
     for (int i=0; i < width; i++) 
     { 
      for (int j=0; j < height; j++) 
      { 
       kernelIndex = uint3(i, j, k); 
       textureIndex = uint3(tid.x + i, tid.y + j, tid.z + k); 
       float4 color = texture_in.read(textureIndex.xy, textureIndex.z).rgba; 
       outColor += color; 
      } 
     } 
     outColor = outColor/(width * height); 
     texture_out.write(float4(outColor.rgba), tid.xy, textureIndex.z); 
    } 
} 

回答

0

Mr.Bista 我有這個同樣的問題,蘋果並沒有爲此提供了一些功能,速度快。 我只是在內核之前使用MPSCNNPoolingAverage來計算平均值。 也許這是一個臨時的方法。 等算法並不比這個好,比如我用代碼測試後的還原和算法。 所以我會繼續跟蹤更好的實現。

+0

哇!好主意..!! 我平均與mpscnnpoolingaverage後,你能給我一些提示如何獲得變化..? –

+0

在mpscnnpoolingaverage之後,您可以使用nchannelx1x1(1x1像素)獲得mpstemporaryimage。然後你可以使用一個內核從原始圖像中計算出子圖像的子和功率,再次進行平均,你會得到方差。 – Ericking

+0

在Github的MetalImage項目中,我將給出另一個帶約簡的算法,參考INVIDA優化算法。(https://github.com/erickingxu/MetalImage.git) – Ericking