簡體   English   中英

如何在Theano中的矩陣上逐元素執行模版計算?

[英]How to perform stencil computations element-wise on a matrix in Theano?

我需要將以下模糊內核應用於RGB圖像中的每個像素

[ 0.0625 0.025 0.375 0.025 0.0625 ]  

因此,偽代碼在Numpy中看起來像這樣

for i in range(rows):
    for j in range(cols):
        for k in range(3):
            final[i][j][k] = image[i-2][j][k]*0.0625 + \
                             image[i-1][j][k]*0.25 + \
                             image[i][j][k]*0.375 + \
                             image[i+1][j][k]*0.25 + \
                             image[i+2][j][k]*0.0625

我曾嘗試搜索與此類似的問題,但從未在計算中找到這種數據訪問方式。
如何為Theano張量矩陣執行上述功能?

您可以將Conv2D函數用於此任務。 請參閱此處的參考,也許您也可以在此處閱讀示例教程。 此解決方案的注意事項:

  • 因為您的內核是對稱的,所以可以忽略filter_flip參數
  • Conv2D使用4D輸入和內核形狀作為參數,因此您需要先對其進行重塑
  • Conv2D對每個通道求和(我認為在您的情況下,“ k”變量適用於RGB,對嗎?它稱為通道),因此應首先將其分開

這是我的示例代碼,我在這里使用更簡單的內核:

import numpy as np
import theano
import theano.tensor as T
from theano.tensor.nnet import conv2d

# original image
img = [[[1, 2, 3, 4], #R channel
       [1, 1, 1, 1],  #
       [2, 2, 2, 2]], #

      [[1, 1, 1, 1],  #G channel
       [2, 2, 2, 2],  #
       [1, 2, 3, 4]], #

      [[1, 1, 1, 1],  #B channel
       [1, 2, 3, 4],  #
       [2, 2, 2, 2],]]#

# separate and reshape each channel to 4D 
R = np.asarray([[img[0]]], dtype='float32')
G = np.asarray([[img[1]]], dtype='float32')
B = np.asarray([[img[2]]], dtype='float32')       

# 4D kernel from the original : [1,0,1] 
kernel = np.asarray([[[[1],[0],[1]]]], dtype='float32')

# theano convolution
t_img = T.ftensor4("t_img")
t_kernel = T.ftensor4("t_kernel")
result = conv2d(
            input = t_img,
            filters=t_kernel,
            filter_shape=(1,1,1,3),
            border_mode = 'half')
f = theano.function([t_img,t_kernel],result)

# compute each channel
R = f(R,kernel)
G = f(G,kernel)
B = f(B,kernel)

# reshape again
img = np.asarray([R,G,B])
img = np.reshape(img,(3,3,4))
print img

如果您有任何關於代碼的討論,請發表評論。 希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM