1. 程式人生 > >theano 實現影象區域性對比度歸一化

theano 實現影象區域性對比度歸一化

很多時候我們需要對影象進行區域性對比度歸一化,比如分塊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