很多時候我們需要對圖像進行局部對比度歸一化,比如分塊CNN的預處理階段。theano對此提供了一些比較方便的操作。
局部歸一化的一種簡單形式為:
其中μ和σ分別為局部(例如3x3的小塊)的均值和標准差。
利用代碼說明一下如何實現:
import theano import numpy from theano.sandbox import neighbours from theano import tensor as T from theano import function from skimage import io import time patch = io.imread('test.jpg', True) patch_batch = [] batch_size = 384 # 這里模擬批量處理多個圖像塊 for i in xrange(batch_size): patch_batch.append(patch) _input = T.tensor3('_input') norm_input = T.reshape(_input, T.concatenate([(batch_size,1),_input.shape[1:]]), ndim=4) # neighbours.images2neibs(ten4, neib_shape, neib_step=None, mode='valid'),其中neib_shap為鄰域大小,這里設置為3x3, # neib_step指定步長,我們需要對每一個點進行歸一化,因此設定為(1x1) # 該函數返回一個shape為(batch_size x patch_width x patch_height, 9)的數組,每一行代表每個點的9個鄰居 neibs = neighbours.images2neibs(norm_input, (3, 3), (1, 1), 'wrap_centered') _means = T.mean(neibs, axis=1) _stds = T.std(neibs, axis=1) _flatten_input = _input.flatten() normed_result = (_flatten_input - _means) / (_stds + 1 / 255) # 將結果重新reshape為圖像大小 reshpaed_normed_result = T.reshape(normed_result, _input.shape) shared_patch = theano.shared(numpy.asarray(patch_batch, dtype=theano.config.floatX), borrow=True) calc_norm = function([], reshpaed_normed_result, givens={_input:shared_patch}) start_time = time.clock() dd = calc_norm() end_time = time.clock() print end_time - start_time