├── GenerateTrainingPatches_AISD_noSelect_label_multi.m ├── README.md ├── exc_SDCNN.m ├── init_SDCNN_model.m ├── init_SDCNN_opts.m ├── learning_rate_policy.m ├── main_test_SDCNN_HighImage.m ├── main_test_SDCNN_epoch.m ├── main_train_SDCNN_BCE.m ├── utils ├── AddBilinearUpSampling.m ├── Cal_PSNRSSIM.m ├── IFC │ ├── distsub_est_M.m │ ├── ifcvec.m │ ├── ind2wtree.m │ ├── readme.txt │ └── refparams_vecgsm.m ├── accuracy.m ├── accuracy_indiv.m ├── batch_imread.m ├── bilinear_kernel.m ├── bilinear_u.m ├── copy_model_weights.m ├── count_network_parameters.m ├── data_augmentation.m ├── evaluate_SR.m ├── learning_rate_policy.m ├── load_list.m ├── matlabPyrTools │ ├── ChangeLog │ ├── Contents.m │ ├── MEX │ │ ├── -MacReadMe │ │ ├── compilePyrTools.m │ │ ├── convolve.c │ │ ├── convolve.h │ │ ├── corrDn.c │ │ ├── corrDn.mexa64 │ │ ├── corrDn.mexglx │ │ ├── corrDn.mexmac │ │ ├── corrDn.mexmaci │ │ ├── corrDn.mexmaci64 │ │ ├── corrDn.mexw32 │ │ ├── corrDn.mexw64 │ │ ├── edges-orig.c │ │ ├── edges.c │ │ ├── histo.c │ │ ├── histo.mexa64 │ │ ├── histo.mexglx │ │ ├── histo.mexmac │ │ ├── histo.mexmaci │ │ ├── histo.mexmaci64 │ │ ├── histo.mexw32 │ │ ├── histo.mexw64 │ │ ├── innerProd.c │ │ ├── pointOp.c │ │ ├── pointOp.exp │ │ ├── pointOp.lib │ │ ├── pointOp.mexa64 │ │ ├── pointOp.mexglx │ │ ├── pointOp.mexmac │ │ ├── pointOp.mexmaci │ │ ├── pointOp.mexmaci64 │ │ ├── pointOp.mexw32 │ │ ├── pointOp.mexw64 │ │ ├── pointOp.mexw64.manifest │ │ ├── range2.c │ │ ├── range2.mexa64 │ │ ├── range2.mexglx │ │ ├── range2.mexmac │ │ ├── range2.mexmaci │ │ ├── range2.mexmaci64 │ │ ├── range2.mexw32 │ │ ├── range2.mexw64 │ │ ├── upConv.c │ │ ├── upConv.exp │ │ ├── upConv.lib │ │ ├── upConv.mexa64 │ │ ├── upConv.mexglx │ │ ├── upConv.mexmac │ │ ├── upConv.mexmaci │ │ ├── upConv.mexmaci64 │ │ ├── upConv.mexw32 │ │ ├── upConv.mexw64 │ │ ├── upConv.mexw64.manifest │ │ └── wrap.c │ ├── README │ ├── TUTORIALS │ │ ├── HTML │ │ │ └── lcv.css │ │ ├── README │ │ ├── matlabPyrTools.html │ │ ├── matlabPyrTools.m │ │ ├── pyramids.html │ │ └── pyramids.m │ ├── binomialFilter.m │ ├── blur.m │ ├── blurDn.m │ ├── buildGpyr.m │ ├── buildLpyr.m │ ├── buildSCFpyr.m │ ├── buildSCFpyrLevs.m │ ├── buildSFpyr.m │ ├── buildSFpyrLevs.m │ ├── buildSpyr.m │ ├── buildSpyrLevs.m │ ├── buildWpyr.m │ ├── cconv2.m │ ├── clip.m │ ├── corrDn.m │ ├── corrDn.mexa64 │ ├── corrDn.mexglx │ ├── corrDn.mexmac │ ├── corrDn.mexmaci64 │ ├── corrDn.mexw32 │ ├── einstein.pgm │ ├── entropy2.m │ ├── factorial.m │ ├── feynman.pgm │ ├── histo.m │ ├── histo.mexa64 │ ├── histo.mexglx │ ├── histo.mexmac │ ├── histo.mexmaci64 │ ├── histo.mexw32 │ ├── histoMatch.m │ ├── imGradient.m │ ├── imStats.m │ ├── innerProd.m │ ├── kurt2.m │ ├── lplot.m │ ├── lpyrHt.m │ ├── make-tar-file │ ├── maxPyrHt.m │ ├── mean2.m │ ├── mkAngle.m │ ├── mkAngularSine.m │ ├── mkDisc.m │ ├── mkFract.m │ ├── mkGaussian.m │ ├── mkImpulse.m │ ├── mkR.m │ ├── mkRamp.m │ ├── mkSine.m │ ├── mkSquare.m │ ├── mkZonePlate.m │ ├── modulateFlip.m │ ├── namedFilter.m │ ├── nextFig.m │ ├── pgmRead.m │ ├── pgmWrite.m │ ├── pixelAxes.m │ ├── pointOp.m │ ├── pointOp.mexa64 │ ├── pointOp.mexglx │ ├── pointOp.mexmac │ ├── pointOp.mexmaci64 │ ├── pointOp.mexw32 │ ├── pwd2path.m │ ├── pyrBand.m │ ├── pyrBandIndices.m │ ├── pyrLow.m │ ├── pyrTools.pdf │ ├── range2.m │ ├── range2.mexa64 │ ├── range2.mexglx │ ├── range2.mexmac │ ├── range2.mexmaci64 │ ├── range2.mexw32 │ ├── rconv2.m │ ├── rcosFn.m │ ├── reconLpyr.m │ ├── reconSCFpyr.m │ ├── reconSFpyr.m │ ├── reconSFpyrLevs.m │ ├── reconSpyr.m │ ├── reconSpyrLevs.m │ ├── reconWpyr.m │ ├── setPyrBand.m │ ├── shift.m │ ├── showIm.m │ ├── showLpyr.m │ ├── showSpyr.m │ ├── showWpyr.m │ ├── skew2.m │ ├── sp0Filters.m │ ├── sp1Filters.m │ ├── sp3Filters.m │ ├── sp5Filters.m │ ├── spyrBand.m │ ├── spyrHigh.m │ └── spyrHt.m ├── mcnExtraLayers-master.zip ├── mcnExtraLayers-master │ ├── LICENSE.md │ ├── README.md │ ├── matlab │ │ ├── +dagnn │ │ │ ├── Axpy.m │ │ │ ├── CaffePooling.m │ │ │ ├── ChannelShuffle.m │ │ │ ├── ClassPrecision.m │ │ │ ├── ClassRecall.m │ │ │ ├── CosineSim.m │ │ │ ├── ErrorStats.m │ │ │ ├── EuclideanLoss.m │ │ │ ├── Flatten.m │ │ │ ├── GlobalPooling.m │ │ │ ├── HuberLoss.m │ │ │ ├── Interp.m │ │ │ ├── L2Norm.m │ │ │ ├── Max.m │ │ │ ├── Normalize.m │ │ │ ├── Permute.m │ │ │ ├── Reshape.m │ │ │ ├── Slice.m │ │ │ ├── SoftMaxTranspose.m │ │ │ ├── SoftmaxCELoss.m │ │ │ ├── TukeyLoss.m │ │ │ └── VerboseLoss.m │ │ ├── vl_nnaugdata.m │ │ ├── vl_nnaxpy.m │ │ ├── vl_nnbrenorm.m │ │ ├── vl_nnbrenorm_auto.m │ │ ├── vl_nncaffepool.m │ │ ├── vl_nnchannelshuffle.m │ │ ├── vl_nncosineloss.m │ │ ├── vl_nncosinesim.m │ │ ├── vl_nncrop_wrapper.m │ │ ├── vl_nneuclideanloss.m │ │ ├── vl_nnflatten.m │ │ ├── vl_nnglobalpool.m │ │ ├── vl_nngnorm.m │ │ ├── vl_nnhuberloss.m │ │ ├── vl_nninterp.m │ │ ├── vl_nnl2norm.m │ │ ├── vl_nnmasknan.m │ │ ├── vl_nnmax.m │ │ ├── vl_nnnonorm.m │ │ ├── vl_nnreshape.m │ │ ├── vl_nnrmse.m │ │ ├── vl_nnscale.m │ │ ├── vl_nnscalenorm.m │ │ ├── vl_nnslice.m │ │ ├── vl_nnsoftmaxceloss.m │ │ ├── vl_nnsoftmaxt.m │ │ ├── vl_nnspatialsoftmax.m │ │ ├── vl_nnsum.m │ │ ├── vl_nntukeyloss.m │ │ ├── wrappers │ │ │ └── vl_nnbrenorm_wrapper.m │ │ └── xtest │ │ │ ├── compare.m │ │ │ ├── run_brenorm_tests.m │ │ │ ├── run_extra_layers_tests.m │ │ │ └── suite │ │ │ ├── dev │ │ │ └── nnl2norm.m │ │ │ ├── nnaxpy.m │ │ │ ├── nnbrenorm.m │ │ │ ├── nncaffepool.m │ │ │ ├── nncosinesim.m │ │ │ ├── nncrop_wrapper.m │ │ │ ├── nneuclideanloss.m │ │ │ ├── nnflatten.m │ │ │ ├── nnglobalpool.m │ │ │ ├── nngnorm.m │ │ │ ├── nnhuberloss.m │ │ │ ├── nninterp.m │ │ │ ├── nnmasknan.m │ │ │ ├── nnmax.m │ │ │ ├── nnnonorm.m │ │ │ ├── nnreshape.m │ │ │ ├── nnscale.m │ │ │ ├── nnscalenorm.m │ │ │ ├── nnslice.m │ │ │ ├── nnsoftmaxceloss.m │ │ │ ├── nnsoftmaxt.m │ │ │ └── nntukeyloss.m │ ├── setup_mcnExtraLayers.m │ ├── test_mcnExtraLayers.m │ └── utils │ │ ├── checkLearningParams.m │ │ ├── extras_autonn_custom_fn.m │ │ ├── fetchExternalImdb.m │ │ └── findBestEpoch.m ├── mod_crop.m ├── modcrop.m ├── model2dot.m ├── patches_generation.m ├── rgb2hsi.m ├── save_matrix.m ├── shave.m └── shave_bd.m ├── vllab_cnn_train_dagNN_multi_label.m └── vllab_nn_L2_loss.m /GenerateTrainingPatches_AISD_noSelect_label_multi.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/GenerateTrainingPatches_AISD_noSelect_label_multi.m -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Aerial Imagery dataset for Shadow Detection (AISD) 2 | Shuang Luo, Huifang Li, Huanfeng Shen. “Deeply supervised convolutional neural network for shadow detection based on a novel aerial shadow imagery dataset”. ISPRS Journal of Photogrammetry and Remote Sensing, 2020. 3 | 4 | ## Download 5 | Our AISD dataset is available for download at Baidu Wangpan. 6 | 7 | Baidu Wangpan Link: https://pan.baidu.com/s/19AtO2Y7r5wDZs0PQgA5eug (password: mhxt) 8 | 9 | ## Acknowledgments 10 | The authors would like to thank Xin Shen, Zhilin Liu, Hongni Ruan, Hao Yu, and Yizhen Li from Wuhan University, Wuhan, China, to help with constructing the dataset. 11 | 12 | ## License 13 | The AISD dataset can only be used for research and Non-Commercial purposes. 14 | -------------------------------------------------------------------------------- /exc_SDCNN.m: -------------------------------------------------------------------------------- 1 | function [output, time] = exc_SDCNN(input, net, gpu) 2 | % ------------------------------------------------------------------------- 3 | % Description: 4 | % function to apply SDCNN 5 | % 6 | % Input: 7 | % - input : original shadow image 8 | % - net : SDCNN model 9 | % - gpu : GPU ID 10 | % 11 | % Output: 12 | % - output: shadow detection result 13 | % 14 | % Citation: 15 | % Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution 16 | % Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang 17 | % IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017 18 | % 19 | % Contact: 20 | % Wei-Sheng Lai 21 | % wlai24@ucmerced.edu 22 | % University of California, Merced 23 | % ------------------------------------------------------------------------- 24 | 25 | %% setup 26 | net.mode = 'test' ; 27 | output_var = 'prediction'; 28 | output_index = net.getVarIndex(output_var); 29 | net.vars(output_index).precious = 1; 30 | 31 | % convert to GPU 32 | y = single(input); 33 | 34 | if( gpu ) 35 | y = gpuArray(y); 36 | end 37 | 38 | % forward 39 | tic; 40 | inputs = {'input', y}; 41 | net.eval(inputs); 42 | time = toc; 43 | 44 | y = gather(net.vars(output_index).value); 45 | 46 | output = double(y); 47 | 48 | end -------------------------------------------------------------------------------- /init_SDCNN_model.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/init_SDCNN_model.m -------------------------------------------------------------------------------- /init_SDCNN_opts.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/init_SDCNN_opts.m -------------------------------------------------------------------------------- /learning_rate_policy.m: -------------------------------------------------------------------------------- 1 | function lr_all = learning_rate_policy(init_lr, step, drop, min_lr, num_epochs) 2 | % ------------------------------------------------------------------------- 3 | % Description: 4 | % function to generate a set of learning rates for each epoch 5 | % 6 | % Input: 7 | % - init_lr : initial learning rate 8 | % - step : number of epochs to drop learning rate 9 | % - drop : learning rate drop ratio 10 | % - min_lr : minimum learning rate 11 | % - num_epochs: total number of epochs 12 | % 13 | % Output: 14 | % - lr_all : learning rate for epochs 15 | % 16 | % Citation: 17 | % Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution 18 | % Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang 19 | % IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017 20 | % 21 | % Contact: 22 | % Wei-Sheng Lai 23 | % wlai24@ucmerced.edu 24 | % University of California, Merced 25 | % ------------------------------------------------------------------------- 26 | 27 | if( drop == 0 ) 28 | lr_all = repmat(init_lr, 1, num_epochs); 29 | else 30 | num_drop = round(num_epochs / step) - 1; 31 | lr_all = init_lr * drop.^(0:num_drop); 32 | lr_all = repmat(lr_all, step, 1); 33 | lr_all = lr_all(:); 34 | end 35 | 36 | lr_all = max(lr_all, min_lr); 37 | end -------------------------------------------------------------------------------- /main_test_SDCNN_HighImage.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/main_test_SDCNN_HighImage.m -------------------------------------------------------------------------------- /main_test_SDCNN_epoch.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/main_test_SDCNN_epoch.m -------------------------------------------------------------------------------- /utils/AddBilinearUpSampling.m: -------------------------------------------------------------------------------- 1 | function net = AddBilinearUpSampling(net, var_to_up_sample, upsampled_var, upsample_fac, opts) 2 | filters = single(bilinear_u(upsample_fac*2, opts.num_classes, opts.num_classes)) ; 3 | % filters = single(bilinear_u(upsample_fac*2, 1, 1)) ; 4 | % filters = single(bilinear_kernel(upsample_fac*2, opts.num_classes, opts.num_classes)) ; 5 | % filters = single(bilinear_kernel(4, 1, 1)) ; 6 | crop = upsample_fac/2; 7 | deconv_name = ['dec_' upsampled_var]; 8 | net.addLayer(deconv_name, ... 9 | dagnn.ConvTranspose('size', size(filters), ... 10 | 'upsample', upsample_fac, ... 11 | 'crop', [crop crop crop crop], ... 12 | 'opts', {'cudnn','nocudnn'}, ... 13 | 'numGroups', opts.num_classes, ... 14 | 'hasBias', false), ... 15 | var_to_up_sample, upsampled_var, [deconv_name 'f']) ; 16 | f = net.getParamIndex([deconv_name 'f']) ; 17 | net.params(f).value = filters ; 18 | net.params(f).learningRate = 0 ; 19 | net.params(f).weightDecay = 1 ; 20 | % net.params(f).trainMethod = 'nothing'; 21 | 22 | -------------------------------------------------------------------------------- /utils/IFC/ind2wtree.m: -------------------------------------------------------------------------------- 1 | function wtree = ind2wtree(pyr, ind) 2 | 3 | %this function is called by vifvec.m 4 | % converts the output of Eero Simoncelli's pyramid routines into subbands in a cell array 5 | C=pyr; 6 | S=ind; 7 | 8 | offset=0; 9 | numsubs=size(ind,1); 10 | for i=1:numsubs 11 | wtree{numsubs-i+1}=reshape(C(offset+1:offset+prod(S(i,:))), S(i,1),S(i,2)); 12 | offset=offset+prod(S(i,:)); 13 | end 14 | -------------------------------------------------------------------------------- /utils/IFC/refparams_vecgsm.m: -------------------------------------------------------------------------------- 1 | function [ssarr, l_arr, cu_arr]=refparams_vecgsm(org,subands,M) 2 | 3 | %This function computes the parameters of the reference image. This is 4 | %called by vifvec.m. 5 | 6 | for i=1:length(subands); 7 | sub=subands(i); 8 | y=org{sub}; 9 | 10 | sizey=floor(size(y)./M)*M; % crop to exact multiple size 11 | y=y(1:sizey(1),1:sizey(2)); 12 | 13 | 14 | % Collect MxM blocks. Rearrange each block into an 15 | % M^2 dimensional vector and collect all such vectors. 16 | % Collece ALL possible MXM blocks (even those overlapping) from the subband 17 | temp=[]; 18 | for j=1:M 19 | for k=1:M 20 | temp=cat(1,temp,reshape(y(k:end-(M-k), j:end-(M-j)),1,[])); 21 | end 22 | end 23 | 24 | % estimate mean and covariance 25 | mcu=mean(temp')'; 26 | cu=((temp-repmat(mcu,1,size(temp,2)))*(temp-repmat(mcu,1,size(temp,2)))')./size(temp,2); % covariance matrix for U 27 | 28 | % Collect MxM blocks as above. Use ONLY non-overlapping blocks to 29 | % calculate the S field 30 | temp=[]; 31 | for j=1:M 32 | for k=1:M 33 | temp=cat(1,temp,reshape(y(k:M:end, j:M:end),1,[])); 34 | end 35 | end 36 | 37 | % Calculate the S field 38 | ss=(inv(cu)*temp); 39 | ss=sum(ss.*temp)./(M*M); 40 | ss=reshape(ss,sizey/M); 41 | 42 | % Eigen-decomposition 43 | [v,d]=eig(cu); 44 | l_arr(sub,:)=diag(d)'; 45 | 46 | % rearrange for output 47 | ssarr{sub}=ss; 48 | temp=0; 49 | d=diag(d); 50 | cu_arr{sub}=cu; 51 | end 52 | 53 | -------------------------------------------------------------------------------- /utils/accuracy.m: -------------------------------------------------------------------------------- 1 | function acc = accuracy(result,GT) 2 | % ------------------------------------------------------------------------- 3 | % Description: 4 | % Shadow Detection Accuracy Assessment 5 | % 6 | % Input: 7 | % - result : shadow detection result 8 | % - GT : shadow ground truth 9 | % 10 | % Output: 11 | % - acc : shadow detection accuracy 12 | % 13 | % ------------------------------------------------------------------------- 14 | 15 | %% Initial setting 16 | % Get the size of the input image 17 | [m,n] = size(result); 18 | 19 | % Set the original data 20 | TP = 0; % true positive, the number of true shadow pixels which are identified correctly 21 | TN = 0; % true negative, the number of nonshadow pixels which are identified correctly 22 | FP = 0; % false positive, the number of nonshadow pixels which are identified as true shadow pixels 23 | FN = 0; % false negative, the number of true shadow pixels which are identified as nonshadow pixels 24 | 25 | %% Statistics 26 | % Compute the Accuracy metrics 27 | sum = m*n; 28 | for i = 1:m 29 | for j = 1:n 30 | if result(i,j) == 1 && GT(i,j) == 1 31 | TP = TP +1; 32 | elseif result(i,j) == 0 && GT(i,j) == 0 33 | TN = TN +1; 34 | elseif result(i,j) == 1 && GT(i,j) == 0 35 | FP = FP +1; 36 | elseif result(i,j) == 0 && GT(i,j) == 1 37 | FN = FN +1; 38 | end 39 | end 40 | end 41 | 42 | %% Accuracy indexes 43 | % For BER index, the lower its value, the better the detection result is. 44 | % Other indexes, the higher, the better. 45 | 46 | % Producer's accuracies 47 | pro_s = double(TP)/double(TP+FN); 48 | pro_n = double(TN)/double(FP+TN); 49 | 50 | % User's accuracies 51 | user_s = double(TP)/double(TP+FP); 52 | user_n = double(TN)/double(TN+FN); 53 | 54 | % Overall accuracy 55 | Total = double(TP+TN)/double(sum); 56 | 57 | % F-score accuracy 58 | F = (2*pro_s*user_s)/(pro_s+user_s); 59 | 60 | % Balance Error Rate (BER) 61 | BER = 1-(pro_s+pro_n)/2; 62 | 63 | % Output as a matrix 64 | % acc = zeros(7,2); 65 | % acc(7,1) = ('pro_s','pro_n','user_s','user_n','Total','F-score','BER'); 66 | %acc = cat(1,pro_s, pro_n, user_s, user_n, Total, F, BER); 67 | %acc = zeros(1,7); 68 | acc = cat(2,pro_s, pro_n, user_s, user_n, Total, F, BER); 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /utils/batch_imread.m: -------------------------------------------------------------------------------- 1 | function img_list = batch_imread(batch) 2 | % ------------------------------------------------------------------------- 3 | % Description: 4 | % read a batch of images 5 | % 6 | % Input: 7 | % - batch : array of ID to fetch 8 | % 9 | % Output: 10 | % - img_list: batch of images 11 | % 12 | % Citation: 13 | % Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution 14 | % Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang 15 | % IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017 16 | % 17 | % Contact: 18 | % Wei-Sheng Lai 19 | % wlai24@ucmerced.edu 20 | % University of California, Merced 21 | % ------------------------------------------------------------------------- 22 | 23 | img_list = cell(length(batch), 1); 24 | 25 | for i = 1:length(batch) 26 | img = imread(batch{i}); 27 | 28 | if( size(img, 3) > 1 ) 29 | img = rgb2ycbcr(img); 30 | img = img(:, :, 1); 31 | end 32 | 33 | img_list{i} = im2single(img); 34 | end 35 | 36 | end -------------------------------------------------------------------------------- /utils/bilinear_kernel.m: -------------------------------------------------------------------------------- 1 | function f = bilinear_kernel(k, num_input, num_output) 2 | % ------------------------------------------------------------------------- 3 | % Description: 4 | % create bilinear interpolation kernel for the convt (deconv) layer 5 | % 6 | % Input: 7 | % - k : kernel size k x k 8 | % - num_input : number of input channels 9 | % - num_output : number of output channels 10 | % 11 | % Output: 12 | % - f : bilinear filter 13 | % 14 | % Citation: 15 | % Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution 16 | % Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang 17 | % IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017 18 | % 19 | % Contact: 20 | % Wei-Sheng Lai 21 | % wlai24@ucmerced.edu 22 | % University of California, Merced 23 | % ------------------------------------------------------------------------- 24 | 25 | 26 | radius = ceil(k / 2); 27 | 28 | if rem(k, 2) == 1 29 | center = radius; 30 | else 31 | center = radius + 0.5; 32 | end 33 | 34 | C = 1:k; 35 | f = (ones(1, k) - abs(C - center) ./ radius)' ... 36 | * (ones(1, k) - abs(C - center) ./ radius); 37 | 38 | f = repmat(f, 1, 1, num_input, num_output); 39 | 40 | 41 | end 42 | 43 | -------------------------------------------------------------------------------- /utils/bilinear_u.m: -------------------------------------------------------------------------------- 1 | function f = bilinear_u(k, numGroups, numClasses) 2 | %BILINEAR_U Create bilinear interpolation filters 3 | % BILINEAR_U(K, NUMGROUPS, NUMCLASSES) compute a square bilinear filter 4 | % of size k for deconv layer of depth numClasses and number of groups 5 | % numGroups 6 | 7 | factor = floor((k+1)/2) ; 8 | if rem(k,2)==1 9 | center = factor ; 10 | else 11 | center = factor + 0.5 ; 12 | end 13 | C = 1:k ; 14 | if numGroups ~= numClasses 15 | f = zeros(k,k,numGroups,numClasses) ; 16 | else 17 | f = zeros(k,k,1,numClasses) ; 18 | end 19 | 20 | for i =1:numClasses 21 | if numGroups ~= numClasses 22 | index = i ; 23 | else 24 | index = 1 ; 25 | end 26 | f(:,:,index,i) = (ones(1,k) - abs(C-center)./factor)'*(ones(1,k) - abs(C-center)./(factor)); 27 | end 28 | end 29 | 30 | -------------------------------------------------------------------------------- /utils/copy_model_weights.m: -------------------------------------------------------------------------------- 1 | function model = copy_model_weights(model, model_trained) 2 | % ------------------------------------------------------------------------- 3 | % Description: 4 | % Copy the weights (parameters) of a pre-trained model to another 5 | % model 6 | % 7 | % Input: 8 | % - model : model to be initialized 9 | % - model_trained : pre-trained model 10 | % 11 | % Output: 12 | % - model : model with copied weights 13 | % 14 | % Citation: 15 | % Fast and Accurate Image Super-Resolution with Deep Laplacian Pyramid Networks 16 | % Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang 17 | % arXiv, 2017 18 | % 19 | % Contact: 20 | % Wei-Sheng Lai 21 | % wlai24@ucmerced.edu 22 | % University of California, Merced 23 | % ------------------------------------------------------------------------- 24 | 25 | for i = 1:length(model.params) 26 | 27 | name = model.params(i).name; 28 | idx = model_trained.getParamIndex(name); 29 | model.params(i).value = model_trained.params(idx).value; 30 | 31 | end 32 | 33 | 34 | end -------------------------------------------------------------------------------- /utils/count_network_parameters.m: -------------------------------------------------------------------------------- 1 | function N = count_network_parameters(net) 2 | % ------------------------------------------------------------------------- 3 | % Description: 4 | % Count the total number of network parameters 5 | % 6 | % Input: 7 | % - net : network 8 | % 9 | % Output: 10 | % - N : #parameters 11 | % 12 | % Citation: 13 | % Fast and Accurate Image Super-Resolution with Deep Laplacian Pyramid Networks 14 | % Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang 15 | % arXiv, 2017 16 | % 17 | % Contact: 18 | % Wei-Sheng Lai 19 | % wlai24@ucmerced.edu 20 | % University of California, Merced 21 | % ------------------------------------------------------------------------- 22 | 23 | N = 0; 24 | for i = 1:length(net.params) 25 | 26 | N = N + numel(net.params(i).value); 27 | 28 | end 29 | 30 | 31 | end -------------------------------------------------------------------------------- /utils/data_augmentation.m: -------------------------------------------------------------------------------- 1 | function image = data_augmentation(image, mode) 2 | 3 | if mode == 1 4 | return; 5 | end 6 | 7 | if mode == 2 % flipped 8 | image = flipud(image); 9 | return; 10 | end 11 | 12 | if mode == 3 % rotation 90 13 | image = rot90(image,1); 14 | return; 15 | end 16 | 17 | if mode == 4 % rotation 90 & flipped 18 | image = rot90(image,1); 19 | image = flipud(image); 20 | return; 21 | end 22 | 23 | if mode == 5 % rotation 180 24 | image = rot90(image,2); 25 | return; 26 | end 27 | 28 | if mode == 6 % rotation 180 & flipped 29 | image = rot90(image,2); 30 | image = flipud(image); 31 | return; 32 | end 33 | 34 | if mode == 7 % rotation 270 35 | image = rot90(image,3); 36 | return; 37 | end 38 | 39 | if mode == 8 % rotation 270 & flipped 40 | image = rot90(image,3); 41 | image = flipud(image); 42 | return; 43 | end 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /utils/evaluate_SR.m: -------------------------------------------------------------------------------- 1 | function [PSNR, SSIM, IFC] = evaluate_SR(img_GT, img_HR, scale, compute_ifc) 2 | % ------------------------------------------------------------------------- 3 | % Description: 4 | % Compute PSNR, SSIM and IFC for SR 5 | % We convert RGB image to grayscale and crop boundaries for 'scale' 6 | % pixels 7 | % 8 | % Input: 9 | % - img_GT : Ground truth image 10 | % - img_HR : predicted HR image 11 | % - scale : upsampling scale 12 | % - compute_ifc : evaluate IFC [default = 0 since it's slow] 13 | % 14 | % Citation: 15 | % Fast and Accurate Image Super-Resolution with Deep Laplacian Pyramid Networks 16 | % Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang 17 | % arXiv, 2017 18 | % 19 | % Contact: 20 | % Wei-Sheng Lai 21 | % wlai24@ucmerced.edu 22 | % University of California, Merced 23 | % ------------------------------------------------------------------------- 24 | 25 | if ~exist('compute_ifc', 'var') 26 | compute_ifc = 0; 27 | end 28 | 29 | %% quantize pixel values 30 | img_GT = im2double(im2uint8(img_GT)); 31 | img_HR = im2double(im2uint8(img_HR)); 32 | 33 | %% convert to gray scale 34 | if( size(img_GT, 3) > 1 ) 35 | img_GT = rgb2ycbcr(img_GT); img_GT = img_GT(:, :, 1); 36 | img_HR = rgb2ycbcr(img_HR); img_HR = img_HR(:, :, 1); 37 | end 38 | 39 | %% crop boundary 40 | img_GT = shave_bd(img_GT, scale); 41 | img_HR = shave_bd(img_HR, scale); 42 | 43 | % evaluate 44 | PSNR = psnr(img_GT, img_HR); 45 | SSIM = ssim(img_GT, img_HR); 46 | 47 | % comment IFC to speed up testing 48 | IFC = 0; 49 | if compute_ifc 50 | IFC = ifcvec(img_GT, img_HR); 51 | if( ~isreal(IFC) ) 52 | IFC = 0; 53 | end 54 | end 55 | 56 | end -------------------------------------------------------------------------------- /utils/learning_rate_policy.m: -------------------------------------------------------------------------------- 1 | function lr_all = learning_rate_policy(init_lr, step, drop, min_lr, num_epochs) 2 | % ------------------------------------------------------------------------- 3 | % Description: 4 | % function to generate a set of learning rates for each epoch 5 | % 6 | % Input: 7 | % - init_lr : initial learning rate 8 | % - step : number of epochs to drop learning rate 9 | % - drop : learning rate drop ratio 10 | % - min_lr : minimum learning rate 11 | % - num_epochs: total number of epochs 12 | % 13 | % Output: 14 | % - lr_all : learning rate for epochs 15 | % 16 | % Citation: 17 | % Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution 18 | % Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang 19 | % IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017 20 | % 21 | % Contact: 22 | % Wei-Sheng Lai 23 | % wlai24@ucmerced.edu 24 | % University of California, Merced 25 | % ------------------------------------------------------------------------- 26 | 27 | if( drop == 0 ) 28 | lr_all = repmat(init_lr, 1, num_epochs); 29 | else 30 | num_drop = round(num_epochs / step) - 1; 31 | lr_all = init_lr * drop.^(0:num_drop); 32 | lr_all = repmat(lr_all, step, 1); 33 | lr_all = lr_all(:); 34 | end 35 | 36 | lr_all = max(lr_all, min_lr); 37 | end -------------------------------------------------------------------------------- /utils/load_list.m: -------------------------------------------------------------------------------- 1 | function list = load_list(list_name) 2 | % ------------------------------------------------------------------------- 3 | % Description: 4 | % load a list file that each row is a string/name 5 | % 6 | % Input: 7 | % - list_name: file name of the list 8 | % 9 | % Output: 10 | % - list : a cell array 11 | % 12 | % Citation: 13 | % Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution 14 | % Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang 15 | % IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017 16 | % 17 | % Contact: 18 | % Wei-Sheng Lai 19 | % wlai24@ucmerced.edu 20 | % University of California, Merced 21 | % ------------------------------------------------------------------------- 22 | 23 | f = fopen(list_name); 24 | if( f == -1 ) 25 | error('%s does not exist!', list_name); 26 | end 27 | C = textscan(f, '%s', 'CommentStyle', '#'); 28 | list = C{1}; 29 | fclose(f); 30 | end -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/-MacReadMe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/-MacReadMe -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/compilePyrTools.m: -------------------------------------------------------------------------------- 1 | % This is a script file for compiling the mex versions of the Steerable 2 | % Pyramid Tools. 3 | % 4 | % Usage:>> compilePyrTools 5 | % 6 | % Tested for gcc and lcc. 7 | % 8 | % Rob Young, 9/08 9 | 10 | mex upConv.c convolve.c wrap.c edges.c 11 | mex corrDn.c convolve.c wrap.c edges.c 12 | mex histo.c 13 | %mex innerProd.c 14 | mex pointOp.c 15 | mex range2.c 16 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/convolve.h: -------------------------------------------------------------------------------- 1 | /* 2 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 3 | ;;; File: convolve.h 4 | ;;; Author: Simoncelli 5 | ;;; Description: Header file for convolve.c 6 | ;;; Creation Date: 7 | ;;; ---------------------------------------------------------------- 8 | ;;; Object-Based Vision and Image Understanding System (OBVIUS), 9 | ;;; Copyright 1988, Vision Science Group, Media Laboratory, 10 | ;;; Massachusetts Institute of Technology. 11 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 12 | */ 13 | 14 | #include 15 | #include 16 | 17 | #define ABS(x) (((x)>=0) ? (x) : (-(x))) 18 | #define ROOT2 1.4142135623730951 19 | #define REDUCE 0 20 | #define EXPAND 1 21 | #define IS == 22 | #define ISNT != 23 | #define AND && 24 | #define OR || 25 | 26 | typedef int (*fptr)(); 27 | 28 | typedef struct 29 | { 30 | char *name; 31 | fptr func; 32 | } EDGE_HANDLER; 33 | 34 | typedef double image_type; 35 | 36 | fptr edge_function(char *edges); 37 | int internal_reduce(image_type *image, int x_idim, int y_idim, 38 | image_type *filt, image_type *temp, int x_fdim, int y_fdim, 39 | int x_start, int x_step, int x_stop, 40 | int y_start, int y_step, int y_stop, 41 | image_type *result, char *edges); 42 | int internal_expand(image_type *image, 43 | image_type *filt, image_type *temp, int x_fdim, int y_fdim, 44 | int x_start, int x_step, int x_stop, 45 | int y_start, int y_step, int y_stop, 46 | image_type *result, int x_rdim, int y_rdim, char *edges); 47 | int internal_wrap_reduce(image_type *image, int x_idim, int y_idim, 48 | image_type *filt, int x_fdim, int y_fdim, 49 | int x_start, int x_step, int x_stop, 50 | int y_start, int y_step, int y_stop, 51 | image_type *result); 52 | int internal_wrap_expand(image_type *image, image_type *filt, int x_fdim, int y_fdim, 53 | int x_start, int x_step, int x_stop, 54 | int y_start, int y_step, int y_stop, 55 | image_type *result, int x_rdim, int y_rdim); 56 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/corrDn.mexa64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/corrDn.mexa64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/corrDn.mexglx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/corrDn.mexglx -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/corrDn.mexmac: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/corrDn.mexmac -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/corrDn.mexmaci: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/corrDn.mexmaci -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/corrDn.mexmaci64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/corrDn.mexmaci64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/corrDn.mexw32: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/corrDn.mexw32 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/corrDn.mexw64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/corrDn.mexw64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/histo.mexa64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/histo.mexa64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/histo.mexglx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/histo.mexglx -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/histo.mexmac: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/histo.mexmac -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/histo.mexmaci: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/histo.mexmaci -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/histo.mexmaci64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/histo.mexmaci64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/histo.mexw32: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/histo.mexw32 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/histo.mexw64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/histo.mexw64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/innerProd.c: -------------------------------------------------------------------------------- 1 | /* 2 | RES = innerProd(MAT); 3 | Computes mat'*mat 4 | Odelia Schwartz, 8/97. 5 | */ 6 | 7 | #define V4_COMPAT 8 | #include 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | void mexFunction(int nlhs, /* Num return vals on lhs */ 17 | mxArray *plhs[], /* Matrices on lhs */ 18 | int nrhs, /* Num args on rhs */ 19 | const mxArray *prhs[] /* Matrices on rhs */ 20 | ) 21 | { 22 | register double *res, *mat, tmp; 23 | register int len, wid, i, k, j, jlen, ilen, imat, jmat; 24 | mxArray *arg; 25 | 26 | /* get matrix input argument */ 27 | /* should be matrix in which num rows >= num columns */ 28 | arg=prhs[0]; 29 | mat= mxGetPr(arg); 30 | len = (int) mxGetM(arg); 31 | wid = (int) mxGetN(arg); 32 | if ( wid > len ) 33 | printf("innerProd: Warning: width %d is greater than length %d.\n",wid,len); 34 | plhs[0] = (mxArray *) mxCreateDoubleMatrix(wid,wid,mxREAL); 35 | if (plhs[0] == NULL) 36 | mexErrMsgTxt(sprintf("Error allocating %dx%d result matrix",wid,wid)); 37 | res = mxGetPr(plhs[0]); 38 | 39 | for(i=0, ilen=0; i 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/range2.c: -------------------------------------------------------------------------------- 1 | /* 2 | [MIN, MAX] = range2(MTX) 3 | >>> See range2.m for documentation <<< 4 | EPS, 3/97. 5 | */ 6 | 7 | #define V4_COMPAT 8 | #include /* Matlab matrices */ 9 | #include 10 | 11 | #include /* NULL */ 12 | 13 | #define notDblMtx(it) (!mxIsNumeric(it) || !mxIsDouble(it) || mxIsSparse(it) || mxIsComplex(it)) 14 | 15 | void mexFunction(int nlhs, /* Num return vals on lhs */ 16 | mxArray *plhs[], /* Matrices on lhs */ 17 | int nrhs, /* Num args on rhs */ 18 | const mxArray *prhs[] /* Matrices on rhs */ 19 | ) 20 | { 21 | register double temp, mn, mx; 22 | register double *mtx; 23 | register int i, size; 24 | const mxArray *arg; 25 | 26 | if (nrhs != 1) mexErrMsgTxt("requires 1 argument."); 27 | 28 | /* ARG 1: MATRIX */ 29 | arg = prhs[0]; 30 | if notDblMtx(arg) mexErrMsgTxt("MTX arg must be a real non-sparse matrix."); 31 | mtx = mxGetPr(arg); 32 | size = (int) mxGetM(arg) * mxGetN(arg); 33 | 34 | /* FIND min, max values of MTX */ 35 | mn = *mtx; mx = *mtx; 36 | for (i=1; i mx) 42 | mx = temp; 43 | } 44 | 45 | plhs[0] = (mxArray *) mxCreateDoubleMatrix(1,1,mxREAL); 46 | if (plhs[0] == NULL) mexErrMsgTxt("Error allocating result matrix"); 47 | plhs[1] = (mxArray *) mxCreateDoubleMatrix(1,1,mxREAL); 48 | if (plhs[1] == NULL) mexErrMsgTxt("Error allocating result matrix"); 49 | mtx = mxGetPr(plhs[0]); 50 | mtx[0] = mn; 51 | mtx = mxGetPr(plhs[1]); 52 | mtx[0] = mx; 53 | 54 | return; 55 | } 56 | 57 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/range2.mexa64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/range2.mexa64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/range2.mexglx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/range2.mexglx -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/range2.mexmac: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/range2.mexmac -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/range2.mexmaci: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/range2.mexmaci -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/range2.mexmaci64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/range2.mexmaci64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/range2.mexw32: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/range2.mexw32 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/range2.mexw64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/range2.mexw64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/upConv.exp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/upConv.exp -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/upConv.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/upConv.lib -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/upConv.mexa64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/upConv.mexa64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/upConv.mexglx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/upConv.mexglx -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/upConv.mexmac: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/upConv.mexmac -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/upConv.mexmaci: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/upConv.mexmaci -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/upConv.mexmaci64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/upConv.mexmaci64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/upConv.mexw32: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/upConv.mexw32 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/upConv.mexw64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/MEX/upConv.mexw64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/MEX/upConv.mexw64.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/TUTORIALS/HTML/lcv.css: -------------------------------------------------------------------------------- 1 | BODY {margin-left:20; margin-top:5; margin-width:15; margin-height:5; font-family:helvetica,arial,sans-serif} 2 | 3 | P.titledlist {margin-left: 2.4em; text-indent: -2.4em; line-height: 1.3; 4 | margin-top: 1.8ex; margin-bottom: 1.8ex;} 5 | 6 | P.people { margin-top: 0ex; margin-bottom: 0.6ex; margin-left: 12px; 7 | text-indent: -12px; } 8 | 9 | P.research {margin-top: 1ex; margin-bottom: 1ex;} 10 | 11 | UL.compact {list-style-image:none; list-style: inside disc } 12 | 13 | LI.software {margin-top: 1ex; margin-bottom: 0ex;} 14 | 15 | a:link {text-decoration:none;} 16 | 17 | a:visited {text-decoration:none;} 18 | 19 | a:hover {color:blue; text-decoration:underline;} 20 | 21 | a span {display:none;} 22 | 23 | a:hover span {display:block; position:fixed; left:150px; padding:5px; background: #f0f0f0; border: 1px dotted #c0c0c0; opacity: 1;} 24 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/TUTORIALS/README: -------------------------------------------------------------------------------- 1 | 2 | This directory contains some Matlab script files that serve to give 3 | example usage of this code, and also to explain some of the 4 | representations and algorithms. 5 | 6 | The files are NOT meant to be executed from the MatLab prompt (like many 7 | of the MatLab demos). You should instead read through the comments, 8 | executing the subsequent pieces of code. This gives you a chance to 9 | explore as you go... 10 | 11 | matlabPyrTools.m - Example usage of the code in the distribution. 12 | 13 | pyramids.m - An introduction to multi-scale pyramid representations, 14 | covering Laplacian, QMF/Wavelet, and Steerable pyramids. The 15 | file assumes a knowledge of linear systems, matrix algebra, 16 | and 2D Fourier transforms. 17 | 18 | matlabPyrTools.html - Same as matlabPyrTools.m, but formatted in html that 19 | shows sample output. 20 | 21 | pyramids.html - Same as pyramids.m, but formatted in html that shows sample 22 | output. 23 | 24 | more to come.... 25 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/binomialFilter.m: -------------------------------------------------------------------------------- 1 | % KERNEL = binomialFilter(size) 2 | % 3 | % Returns a vector of binomial coefficients of order (size-1) . 4 | 5 | % Eero Simoncelli, 2/97. 6 | 7 | function [kernel] = binomialFilter(sz) 8 | 9 | if (sz < 2) 10 | error('size argument must be larger than 1'); 11 | end 12 | 13 | kernel = [0.5 0.5]'; 14 | 15 | for n=1:sz-2 16 | kernel = conv([0.5 0.5]', kernel); 17 | end 18 | 19 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/blur.m: -------------------------------------------------------------------------------- 1 | % RES = blur(IM, LEVELS, FILT) 2 | % 3 | % Blur an image, by filtering and downsampling LEVELS times 4 | % (default=1), followed by upsampling and filtering LEVELS times. The 5 | % blurring is done with filter kernel specified by FILT (default = 6 | % 'binom5'), which can be a string (to be passed to namedFilter), a 7 | % vector (applied separably as a 1D convolution kernel in X and Y), or 8 | % a matrix (applied as a 2D convolution kernel). The downsampling is 9 | % always by 2 in each direction. 10 | 11 | % Eero Simoncelli, 3/04. 12 | 13 | function res = blur(im, nlevs, filt) 14 | 15 | %------------------------------------------------------------ 16 | %% OPTIONAL ARGS: 17 | 18 | if (exist('nlevs') ~= 1) 19 | nlevs = 1; 20 | end 21 | 22 | if (exist('filt') ~= 1) 23 | filt = 'binom5'; 24 | end 25 | 26 | %------------------------------------------------------------ 27 | 28 | if isstr(filt) 29 | filt = namedFilter(filt); 30 | end 31 | 32 | filt = filt/sum(filt(:)); 33 | 34 | if nlevs > 0 35 | if (any(size(im)==1)) 36 | if (~any(size(filt)==1)) 37 | error('Cant apply 2D filter to 1D signal'); 38 | end 39 | if (size(im,2)==1) 40 | filt = filt(:); 41 | else 42 | filt = filt(:)'; 43 | end 44 | 45 | in = corrDn(im,filt,'reflect1',(size(im)~=1)+1); 46 | out = blur(in, nlevs-1, filt); 47 | res = upConv(out, filt, 'reflect1', (size(im)~=1)+1, [1 1], size(im)); 48 | 49 | elseif (any(size(filt)==1)) 50 | filt = filt(:); 51 | 52 | in = corrDn(im,filt,'reflect1',[2 1]); 53 | in = corrDn(in,filt','reflect1',[1 2]); 54 | out = blur(in, nlevs-1, filt); 55 | res = upConv(out, filt', 'reflect1', [1 2], [1 1], [size(out,1),size(im,2)]); 56 | res = upConv(res, filt, 'reflect1', [2 1], [1 1], size(im)); 57 | 58 | else 59 | 60 | in = corrDn(im,filt,'reflect1',[2 2]); 61 | out = blur(in, nlevs-1, filt); 62 | res = upConv(out, filt, 'reflect1', [2 2], [1 1], size(im)); 63 | end 64 | else 65 | res = im; 66 | end 67 | 68 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/blurDn.m: -------------------------------------------------------------------------------- 1 | % RES = blurDn(IM, LEVELS, FILT) 2 | % 3 | % Blur and downsample an image. The blurring is done with filter 4 | % kernel specified by FILT (default = 'binom5'), which can be a string 5 | % (to be passed to namedFilter), a vector (applied separably as a 1D 6 | % convolution kernel in X and Y), or a matrix (applied as a 2D 7 | % convolution kernel). The downsampling is always by 2 in each 8 | % direction. 9 | % 10 | % The procedure is applied recursively LEVELS times (default=1). 11 | 12 | % Eero Simoncelli, 3/97. 13 | 14 | function res = blurDn(im, nlevs, filt) 15 | 16 | %------------------------------------------------------------ 17 | %% OPTIONAL ARGS: 18 | 19 | if (exist('nlevs') ~= 1) 20 | nlevs = 1; 21 | end 22 | 23 | if (exist('filt') ~= 1) 24 | filt = 'binom5'; 25 | end 26 | 27 | %------------------------------------------------------------ 28 | 29 | if isstr(filt) 30 | filt = namedFilter(filt); 31 | end 32 | 33 | filt = filt/sum(filt(:)); 34 | 35 | if nlevs > 1 36 | im = blurDn(im,nlevs-1,filt); 37 | end 38 | 39 | if (nlevs >= 1) 40 | if (any(size(im)==1)) 41 | if (~any(size(filt)==1)) 42 | error('Cant apply 2D filter to 1D signal'); 43 | end 44 | if (size(im,2)==1) 45 | filt = filt(:); 46 | else 47 | filt = filt(:)'; 48 | end 49 | res = corrDn(im,filt,'reflect1',(size(im)~=1)+1); 50 | elseif (any(size(filt)==1)) 51 | filt = filt(:); 52 | res = corrDn(im,filt,'reflect1',[2 1]); 53 | res = corrDn(res,filt','reflect1',[1 2]); 54 | else 55 | res = corrDn(im,filt,'reflect1',[2 2]); 56 | end 57 | else 58 | res = im; 59 | end 60 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/buildGpyr.m: -------------------------------------------------------------------------------- 1 | % [PYR, INDICES] = buildGpyr(IM, HEIGHT, FILT, EDGES) 2 | % 3 | % Construct a Gaussian pyramid on matrix IM. 4 | % 5 | % HEIGHT (optional) specifies the number of pyramid levels to build. Default 6 | % is 1+maxPyrHt(size(IM),size(FILT)). 7 | % You can also specify 'auto' to use this value. 8 | % 9 | % FILT (optional) can be a string naming a standard filter (see 10 | % namedFilter), or a vector which will be used for (separable) 11 | % convolution. Default = 'binom5'. EDGES specifies edge-handling, and 12 | % defaults to 'reflect1' (see corrDn). 13 | % 14 | % PYR is a vector containing the N pyramid subbands, ordered from fine 15 | % to coarse. INDICES is an Nx2 matrix containing the sizes of 16 | % each subband. This is compatible with the MatLab Wavelet toolbox. 17 | 18 | % Eero Simoncelli, 6/96. 19 | 20 | function [pyr,pind] = buildGpyr(im, ht, filt, edges) 21 | 22 | if (nargin < 1) 23 | error('First argument (IM) is required'); 24 | end 25 | 26 | im_sz = size(im); 27 | 28 | %------------------------------------------------------------ 29 | %% OPTIONAL ARGS: 30 | 31 | if (exist('filt') ~= 1) 32 | filt = 'binom5'; 33 | end 34 | 35 | if isstr(filt) 36 | filt = namedFilter(filt); 37 | end 38 | 39 | if ( (size(filt,1) > 1) & (size(filt,2) > 1) ) 40 | error('FILT should be a 1D filter (i.e., a vector)'); 41 | else 42 | filt = filt(:); 43 | end 44 | 45 | max_ht = 1 + maxPyrHt(im_sz, size(filt,1)); 46 | if ( (exist('ht') ~= 1) | (ht == 'auto') ) 47 | ht = max_ht; 48 | else 49 | if (ht > max_ht) 50 | error(sprintf('Cannot build pyramid higher than %d levels.',max_ht)); 51 | end 52 | end 53 | 54 | if (exist('edges') ~= 1) 55 | edges= 'reflect1'; 56 | end 57 | 58 | %------------------------------------------------------------ 59 | 60 | if (ht <= 1) 61 | 62 | pyr = im(:); 63 | pind = im_sz; 64 | 65 | else 66 | 67 | if (im_sz(2) == 1) 68 | lo2 = corrDn(im, filt, edges, [2 1], [1 1]); 69 | elseif (im_sz(1) == 1) 70 | lo2 = corrDn(im, filt', edges, [1 2], [1 1]); 71 | else 72 | lo = corrDn(im, filt', edges, [1 2], [1 1]); 73 | lo2 = corrDn(lo, filt, edges, [2 1], [1 1]); 74 | end 75 | 76 | [npyr,nind] = buildGpyr(lo2, ht-1, filt, edges); 77 | 78 | pyr = [im(:); npyr]; 79 | pind = [im_sz; nind]; 80 | 81 | end 82 | 83 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/buildSCFpyrLevs.m: -------------------------------------------------------------------------------- 1 | % [PYR, INDICES] = buildSCFpyrLevs(LODFT, LOGRAD, XRCOS, YRCOS, ANGLE, HEIGHT, NBANDS) 2 | % 3 | % Recursive function for constructing levels of a steerable pyramid. This 4 | % is called by buildSCFpyr, and is not usually called directly. 5 | 6 | % Original code: Eero Simoncelli, 5/97. 7 | % Modified by Javier Portilla to generate complex bands in 9/97. 8 | 9 | function [pyr,pind] = buildSCFpyrLevs(lodft,log_rad,Xrcos,Yrcos,angle,ht,nbands); 10 | 11 | if (ht <= 0) 12 | 13 | lo0 = ifft2(ifftshift(lodft)); 14 | pyr = real(lo0(:)); 15 | pind = size(lo0); 16 | 17 | else 18 | 19 | bands = zeros(prod(size(lodft)), nbands); 20 | bind = zeros(nbands,2); 21 | 22 | % log_rad = log_rad + 1; 23 | Xrcos = Xrcos - log2(2); % shift origin of lut by 1 octave. 24 | 25 | lutsize = 1024; 26 | Xcosn = pi*[-(2*lutsize+1):(lutsize+1)]/lutsize; % [-2*pi:pi] 27 | order = nbands-1; 28 | %% divide by sqrt(sum_(n=0)^(N-1) cos(pi*n/N)^(2(N-1)) ) 29 | %% Thanks to Patrick Teo for writing this out :) 30 | const = (2^(2*order))*(factorial(order)^2)/(nbands*factorial(2*order)); 31 | 32 | % 33 | % Ycosn = sqrt(const) * (cos(Xcosn)).^order; 34 | % 35 | % analityc version: only take one lobe 36 | alfa= mod(pi+Xcosn,2*pi)-pi; 37 | Ycosn = 2*sqrt(const) * (cos(Xcosn).^order) .* (abs(alfa) max_ht) 49 | error(sprintf('Cannot build pyramid higher than %d levels.',max_ht)); 50 | end 51 | end 52 | 53 | %----------------------------------------------------------------- 54 | 55 | hi0 = corrDn(im, hi0filt, edges); 56 | lo0 = corrDn(im, lo0filt, edges); 57 | 58 | [pyr,pind] = buildSpyrLevs(lo0, ht, lofilt, bfilts, edges); 59 | 60 | pyr = [hi0(:) ; pyr]; 61 | pind = [size(hi0); pind]; 62 | 63 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/buildSpyrLevs.m: -------------------------------------------------------------------------------- 1 | % [PYR, INDICES] = buildSpyrLevs(LOIM, HEIGHT, LOFILT, BFILTS, EDGES) 2 | % 3 | % Recursive function for constructing levels of a steerable pyramid. This 4 | % is called by buildSpyr, and is not usually called directly. 5 | 6 | % Eero Simoncelli, 6/96. 7 | 8 | function [pyr,pind] = buildSpyrLevs(lo0,ht,lofilt,bfilts,edges); 9 | 10 | if (ht <= 0) 11 | 12 | pyr = lo0(:); 13 | pind = size(lo0); 14 | 15 | else 16 | 17 | % Assume square filters: 18 | bfiltsz = round(sqrt(size(bfilts,1))); 19 | 20 | bands = zeros(prod(size(lo0)),size(bfilts,2)); 21 | bind = zeros(size(bfilts,2),2); 22 | 23 | for b = 1:size(bfilts,2) 24 | filt = reshape(bfilts(:,b),bfiltsz,bfiltsz); 25 | band = corrDn(lo0, filt, edges); 26 | bands(:,b) = band(:); 27 | bind(b,:) = size(band); 28 | end 29 | 30 | lo = corrDn(lo0, lofilt, edges, [2 2], [1 1]); 31 | 32 | [npyr,nind] = buildSpyrLevs(lo, ht-1, lofilt, bfilts, edges); 33 | 34 | pyr = [bands(:); npyr]; 35 | pind = [bind; nind]; 36 | 37 | end 38 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/cconv2.m: -------------------------------------------------------------------------------- 1 | % RES = CCONV2(MTX1, MTX2, CTR) 2 | % 3 | % Circular convolution of two matrices. Result will be of size of 4 | % LARGER vector. 5 | % 6 | % The origin of the smaller matrix is assumed to be its center. 7 | % For even dimensions, the origin is determined by the CTR (optional) 8 | % argument: 9 | % CTR origin 10 | % 0 DIM/2 (default) 11 | % 1 (DIM/2)+1 12 | 13 | % Eero Simoncelli, 6/96. Modified 2/97. 14 | 15 | function c = cconv2(a,b,ctr) 16 | 17 | if (exist('ctr') ~= 1) 18 | ctr = 0; 19 | end 20 | 21 | if (( size(a,1) >= size(b,1) ) & ( size(a,2) >= size(b,2) )) 22 | large = a; small = b; 23 | elseif (( size(a,1) <= size(b,1) ) & ( size(a,2) <= size(b,2) )) 24 | large = b; small = a; 25 | else 26 | error('one arg must be larger than the other in both dimensions!'); 27 | end 28 | 29 | ly = size(large,1); 30 | lx = size(large,2); 31 | sy = size(small,1); 32 | sx = size(small,2); 33 | 34 | %% These values are the index of the small mtx that falls on the 35 | %% border pixel of the large matrix when computing the first 36 | %% convolution response sample: 37 | sy2 = floor((sy+ctr+1)/2); 38 | sx2 = floor((sx+ctr+1)/2); 39 | 40 | % pad: 41 | clarge = [ ... 42 | large(ly-sy+sy2+1:ly,lx-sx+sx2+1:lx), large(ly-sy+sy2+1:ly,:), ... 43 | large(ly-sy+sy2+1:ly,1:sx2-1); ... 44 | large(:,lx-sx+sx2+1:lx), large, large(:,1:sx2-1); ... 45 | large(1:sy2-1,lx-sx+sx2+1:lx), ... 46 | large(1:sy2-1,:), ... 47 | large(1:sy2-1,1:sx2-1) ]; 48 | 49 | c = conv2(clarge,small,'valid'); 50 | 51 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/clip.m: -------------------------------------------------------------------------------- 1 | % [RES] = clip(IM, MINVALorRANGE, MAXVAL) 2 | % 3 | % Clip values of matrix IM to lie between minVal and maxVal: 4 | % RES = max(min(IM,MAXVAL),MINVAL) 5 | % The first argument can also specify both min and max, as a 2-vector. 6 | % If only one argument is passed, the range defaults to [0,1]. 7 | 8 | function res = clip(im, minValOrRange, maxVal) 9 | 10 | if (exist('minValOrRange') ~= 1) 11 | minVal = 0; 12 | maxVal = 1; 13 | elseif (length(minValOrRange) == 2) 14 | minVal = minValOrRange(1); 15 | maxVal = minValOrRange(2); 16 | elseif (length(minValOrRange) == 1) 17 | minVal = minValOrRange; 18 | if (exist('maxVal') ~= 1) 19 | maxVal=minVal+1; 20 | end 21 | else 22 | error('MINVAL must be a scalar or a 2-vector'); 23 | end 24 | 25 | if ( maxVal < minVal ) 26 | error('MAXVAL should be less than MINVAL'); 27 | end 28 | 29 | res = im; 30 | res(find(im < minVal)) = minVal; 31 | res(find(im > maxVal)) = maxVal; 32 | 33 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/corrDn.mexa64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/corrDn.mexa64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/corrDn.mexglx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/corrDn.mexglx -------------------------------------------------------------------------------- /utils/matlabPyrTools/corrDn.mexmac: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/corrDn.mexmac -------------------------------------------------------------------------------- /utils/matlabPyrTools/corrDn.mexmaci64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/corrDn.mexmaci64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/corrDn.mexw32: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/corrDn.mexw32 -------------------------------------------------------------------------------- /utils/matlabPyrTools/einstein.pgm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/einstein.pgm -------------------------------------------------------------------------------- /utils/matlabPyrTools/entropy2.m: -------------------------------------------------------------------------------- 1 | % E = ENTROPY2(MTX,BINSIZE) 2 | % 3 | % Compute the first-order sample entropy of MTX. Samples of VEC are 4 | % first discretized. Optional argument BINSIZE controls the 5 | % discretization, and defaults to 256/(max(VEC)-min(VEC)). 6 | % 7 | % NOTE: This is a heavily biased estimate of entropy (it is too 8 | % small) when you don't have much data! 9 | 10 | % Eero Simoncelli, 6/96. 11 | 12 | function res = entropy2(mtx,binsize) 13 | 14 | %% Ensure it's a vector, not a matrix. 15 | vec = mtx(:); 16 | [mn,mx] = range2(vec); 17 | 18 | if (exist('binsize') == 1) 19 | nbins = max((mx-mn)/binsize, 1); 20 | else 21 | nbins = 256; 22 | end 23 | 24 | [bincount,bins] = histo(vec,nbins); 25 | 26 | %% Collect non-zero bins: 27 | H = bincount(find(bincount)); 28 | H = H/sum(H); 29 | 30 | res = -sum(H .* log2(H)); 31 | 32 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/factorial.m: -------------------------------------------------------------------------------- 1 | %% RES = factorial(NUM) 2 | % 3 | % Factorial function that works on matrices (matlab's does not). 4 | 5 | % EPS, 11/02 6 | 7 | function res = factorial(num) 8 | 9 | res = ones(size(num)); 10 | 11 | ind = find(num > 0); 12 | if ( ~isempty(ind) ) 13 | subNum = num(ind); 14 | res(ind) = subNum .* factorial(subNum-1); 15 | end 16 | 17 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/feynman.pgm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/feynman.pgm -------------------------------------------------------------------------------- /utils/matlabPyrTools/histo.m: -------------------------------------------------------------------------------- 1 | % [N,X] = histo(MTX, nbinsOrBinsize, binCenter); 2 | % 3 | % Compute a histogram of (all) elements of MTX. N contains the histogram 4 | % counts, X is a vector containg the centers of the histogram bins. 5 | % 6 | % nbinsOrBinsize (optional, default = 101) specifies either 7 | % the number of histogram bins, or the negative of the binsize. 8 | % 9 | % binCenter (optional, default = mean2(MTX)) specifies a center position 10 | % for (any one of) the histogram bins. 11 | % 12 | % How does this differ from MatLab's HIST function? This function: 13 | % - allows uniformly spaced bins only. 14 | % +/- operates on all elements of MTX, instead of columnwise. 15 | % + is much faster (approximately a factor of 80 on my machine). 16 | % + allows specification of number of bins OR binsize. Default=101 bins. 17 | % + allows (optional) specification of binCenter. 18 | 19 | % Eero Simoncelli, 3/97. 20 | 21 | function [N, X] = histo(mtx, nbins, binCtr) 22 | 23 | %% NOTE: THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD) 24 | 25 | fprintf(1,'WARNING: You should compile the MEX version of "histo.c",\n found in the MEX subdirectory of matlabPyrTools, and put it in your matlab path. It is MUCH faster.\n'); 26 | 27 | mtx = mtx(:); 28 | 29 | %------------------------------------------------------------ 30 | %% OPTIONAL ARGS: 31 | 32 | [mn,mx] = range2(mtx); 33 | 34 | if (exist('binCtr') ~= 1) 35 | binCtr = mean(mtx); 36 | end 37 | 38 | if (exist('nbins') == 1) 39 | if (nbins < 0) 40 | binSize = -nbins; 41 | else 42 | binSize = ((mx-mn)/nbins); 43 | tmpNbins = round((mx-binCtr)/binSize) - round((mn-binCtr)/binSize); 44 | if (tmpNbins ~= nbins) 45 | warning('Using %d bins instead of requested number (%d)',tmpNbins,nbins); 46 | end 47 | end 48 | else 49 | binSize = ((mx-mn)/101); 50 | end 51 | 52 | firstBin = binCtr + binSize*round( (mn-binCtr)/binSize ); 53 | 54 | tmpNbins = round((mx-binCtr)/binSize) - round((mn-binCtr)/binSize); 55 | 56 | bins = firstBin + binSize*[0:tmpNbins]; 57 | 58 | [N, X] = hist(mtx, bins); 59 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/histo.mexa64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/histo.mexa64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/histo.mexglx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/histo.mexglx -------------------------------------------------------------------------------- /utils/matlabPyrTools/histo.mexmac: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/histo.mexmac -------------------------------------------------------------------------------- /utils/matlabPyrTools/histo.mexmaci64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/histo.mexmaci64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/histo.mexw32: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/histo.mexw32 -------------------------------------------------------------------------------- /utils/matlabPyrTools/histoMatch.m: -------------------------------------------------------------------------------- 1 | % RES = histoMatch(MTX, N, X) 2 | % 3 | % Modify elements of MTX so that normalized histogram matches that 4 | % specified by vectors X and N, where N contains the histogram counts 5 | % and X the histogram bin positions (see histo). 6 | 7 | % Eero Simoncelli, 7/96. 8 | 9 | function res = histoMatch(mtx, N, X) 10 | 11 | if ( exist('histo') == 3 ) 12 | [oN, oX] = histo(mtx(:), size(X(:),1)); 13 | else 14 | [oN, oX] = hist(mtx(:), size(X(:),1)); 15 | end 16 | 17 | oStep = oX(2) - oX(1); 18 | oC = [0, cumsum(oN)]/sum(oN); 19 | oX = [oX(1)-oStep/2, oX+oStep/2]; 20 | 21 | N = N(:)'; 22 | X = X(:)'; 23 | N = N + mean(N)/(1e8); %% HACK: no empty bins ensures nC strictly monotonic 24 | 25 | nStep = X(2) - X(1); 26 | nC = [0, cumsum(N)]/sum(N); 27 | nX = [X(1)-nStep/2, X+nStep/2]; 28 | 29 | nnX = interp1(nC, nX, oC, 'linear'); 30 | 31 | if ( exist('pointOp') == 3 ) 32 | res = pointOp(mtx, nnX, oX(1), oStep); 33 | else 34 | res = reshape(interp1(oX, nnX, mtx(:)),size(mtx,1),size(mtx,2)); 35 | end 36 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/imGradient.m: -------------------------------------------------------------------------------- 1 | % [dx, dy] = imGradient(im, edges) 2 | % 3 | % Compute the gradient of the image using smooth derivative filters 4 | % optimized for accurate direction estimation. Coordinate system 5 | % corresponds to standard pixel indexing: X axis points rightward. Y 6 | % axis points downward. EDGES specify boundary handling (see corrDn 7 | % for options). 8 | % 9 | % Unlike matlab's new gradient function, which is based on local 10 | % differences, this function computes derivatives using 5x5 filters 11 | % designed to accurately reflect the local orientation content. 12 | 13 | % EPS, 1997. 14 | % original filters from Int'l Conf Image Processing, 1994. 15 | % updated filters 10/2003: see Farid & Simoncelli, IEEE Trans Image Processing, 13(4):496-508, April 2004. 16 | % Incorporated into matlabPyrTools 10/2004. 17 | 18 | function [dx, dy] = imGradient(im, edges) 19 | 20 | if (exist('edges') ~= 1) 21 | edges = 'dont-compute'; 22 | end 23 | 24 | %% kernels from Farid & Simoncelli, IEEE Trans Image Processing, 13(4):496-508, April 2004. 25 | gp = [0.037659 0.249153 0.426375 0.249153 0.037659]'; 26 | gd = [-0.109604 -0.276691 0.000000 0.276691 0.109604]'; 27 | 28 | dx = corrDn(corrDn(im, gp, edges), gd', edges); 29 | dy = corrDn(corrDn(im, gd, edges), gp', edges); 30 | 31 | return 32 | 33 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 34 | %%% TEST: 35 | 36 | %%Make a ramp with random slope and direction 37 | dir = 2*pi*rand - pi; 38 | slope = 10*rand; 39 | 40 | sz = 32 41 | im = mkRamp(sz, dir, slope); 42 | [dx,dy] = imGradient(im); 43 | showIm(dx + sqrt(-1)*dy); 44 | 45 | ctr = (sz*sz/2)+sz/2; 46 | slopeEst = sqrt(dx(ctr).^2 + dy(ctr).^2); 47 | dirEst = atan2(dy(ctr), dx(ctr)); 48 | 49 | [slope, slopeEst] 50 | [dir, dirEst] 51 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/imStats.m: -------------------------------------------------------------------------------- 1 | % imStats(IM1,IM2) 2 | % 3 | % Report image (matrix) statistics. 4 | % When called on a single image IM1, report min, max, mean, stdev, skew, 5 | % and kurtosis (4th moment about the mean, divided by squared variance) 6 | % 7 | % When called on two images (IM1 and IM2), report min, max, mean, 8 | % stdev of the difference, and also SNR (relative to IM1). 9 | 10 | % Eero Simoncelli, 6/96. 11 | 12 | function [] = imStats(im1,im2) 13 | 14 | if (~isreal(im1)) 15 | error('Args must be real-valued matrices'); 16 | end 17 | 18 | if (exist('im2') == 1) 19 | difference = im1 - im2; 20 | [mn,mx] = range2(difference); 21 | mean = mean2(difference); 22 | v = var2(difference,mean); 23 | if (v < realmin) 24 | snr = Inf; 25 | else 26 | snr = 10 * log10(var2(im1)/v); 27 | end 28 | fprintf(1, 'Difference statistics:\n'); 29 | fprintf(1, ' Range: [%c, %c]\n',mn,mx); 30 | fprintf(1, ' Mean: %f, Stdev (rmse): %f, SNR (dB): %f\n',... 31 | mean,sqrt(v),snr); 32 | else 33 | [mn,mx] = range2(im1); 34 | mean = mean2(im1); 35 | var = var2(im1,mean); 36 | stdev = sqrt(real(var))+sqrt(imag(var)); 37 | sk = skew2(im1, mean, stdev^2); 38 | kurt = kurt2(im1, mean, stdev^2); 39 | fprintf(1, 'Image statistics:\n'); 40 | fprintf(1, ' Range: [%f, %f]\n',mn,mx); 41 | fprintf(1, ' Mean: %f, Stdev: %f, Skew: %f, Kurt: %f\n',mean,stdev,sk,kurt); 42 | end 43 | 44 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/innerProd.m: -------------------------------------------------------------------------------- 1 | % RES = innerProd(MTX) 2 | % 3 | % Compute (MTX' * MTX) efficiently (i.e., without copying the matrix) 4 | % 5 | % NOTE: This function used to call a MEX function (C code) to avoid copying, but 6 | % newer versions of matlab have eliminated the overhead of the 7 | % simpler form below. 8 | 9 | function res = innerProd(mtx) 10 | 11 | res = mtx' * mtx; 12 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/kurt2.m: -------------------------------------------------------------------------------- 1 | % K = KURT2(MTX,MEAN,VAR) 2 | % 3 | % Sample kurtosis (fourth moment divided by squared variance) 4 | % of a matrix. Kurtosis of a Gaussian distribution is 3. 5 | % MEAN (optional) and VAR (optional) make the computation faster. 6 | 7 | % Eero Simoncelli, 6/96. 8 | 9 | function res = kurt2(mtx, mn, v) 10 | 11 | if (exist('mn') ~= 1) 12 | mn = mean(mean(mtx)); 13 | end 14 | 15 | if (exist('v') ~= 1) 16 | v = var2(mtx,mn); 17 | end 18 | 19 | if (isreal(mtx)) 20 | res = mean(mean(abs(mtx-mn).^4)) / (v^2); 21 | else 22 | res = mean(mean(real(mtx-mn).^4)) / (real(v)^2) + ... 23 | i*mean(mean(imag(mtx-mn).^4)) / (imag(v)^2); 24 | end 25 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/lplot.m: -------------------------------------------------------------------------------- 1 | % lplot(VEC, XRANGE) 2 | % 3 | % Plot VEC, a vector, in "lollipop" format. 4 | % XRANGE (optional, default = [1,length(VEC)]), should be a 2-vector 5 | % specifying the X positions (for labeling purposes) of the first and 6 | % last sample of VEC. 7 | 8 | % Mark Liberman, Linguistics Dept, UPenn, 1994. 9 | 10 | function lplot(x,xrange) 11 | 12 | if (exist('xrange') ~= 1) 13 | xrange = [1,length(x)]; 14 | end 15 | 16 | msize = size(x); 17 | if ( msize(2) == 1) 18 | x = x'; 19 | elseif (msize(1) ~= 1) 20 | error('First arg must be a vector'); 21 | end 22 | 23 | if (~isreal(x)) 24 | fprintf(1,'Warning: Imaginary part of signal ignored\n'); 25 | x = abs(x); 26 | end 27 | 28 | N = length(x); 29 | index = xrange(1) + (xrange(2)-xrange(1))*[0:(N-1)]/(N-1); 30 | xinc = index(2)-index(1); 31 | 32 | xx = [zeros(1,N);x;zeros(1,N)]; 33 | indexis = [index;index;index]; 34 | xdiscrete = [0 xx(:)' 0]; 35 | idiscrete = [index(1)-xinc indexis(:)' index(N)+xinc]; 36 | 37 | [mn,mx] = range2(xdiscrete); 38 | ypad = (mx-mn)/12; % MAGIC NUMBER: graph padding 39 | 40 | plot(idiscrete, xdiscrete, index, x, 'o'); 41 | axis([index(1)-xinc, index(N)+xinc, mn-ypad, mx+ypad]); 42 | 43 | return 44 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/lpyrHt.m: -------------------------------------------------------------------------------- 1 | % [HEIGHT] = lpyrHt(INDICES) 2 | % 3 | % Compute height of Laplacian pyramid with given its INDICES matrix. 4 | % See buildLpyr.m 5 | 6 | % Eero Simoncelli, 6/96. 7 | 8 | function [ht] = lpyrHt(pind) 9 | 10 | % Don't count lowpass residual band 11 | ht = size(pind,1)-1; 12 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/make-tar-file: -------------------------------------------------------------------------------- 1 | #!/bin/csh -f 2 | 3 | setenv BASENAME "/lcv/matlab/lib/" 4 | 5 | setenv DIRNAME "matlabPyrTools" 6 | setenv TARFILE "matlabPyrTools.tar" 7 | 8 | # For MAC: 9 | # Put Macintosh-MEX.sit.hqx (contains projects, C code, mex files) inside of 10 | # MEX directory. 11 | # Put matlabPyrTools.sit.hqx (entire distribution, filetype corrected, no 12 | # MEX subdirectory) inside of main directory. 13 | 14 | #################################################################### 15 | ## Make a compressed tar file of the EPS_matlab directory: 16 | 17 | echo "Before making the tar file:" 18 | echo "1) If C code is modified, re-make the mex files..." 19 | echo "2) Put correct date and version number in Contents.m. Execute 'ver' to test" 20 | echo "3) add a ChangeLog entry stating that new tarfile was generated" 21 | sleep 5 22 | 23 | pushd ${BASENAME} 24 | 25 | #echo "Removing old tarfile..." 26 | #/bin/rm "${DIRNAME}/${TARFILE}" 27 | #/bin/rm "${DIRNAME}/${TARFILE}.gz" 28 | 29 | #echo "Removing ${DIRNAME}/MEX/*.o files..." 30 | #/bin/rm ${DIRNAME}/MEX/*.o 31 | 32 | echo "Creating ${DIRNAME}/${TARFILE} ..." 33 | 34 | tar -cvf ${DIRNAME}/${TARFILE} \ 35 | ${DIRNAME}/README ${DIRNAME}/ChangeLog ${DIRNAME}/*.m \ 36 | ${DIRNAME}/MEX \ 37 | ${DIRNAME}/TUTORIALS/README ${DIRNAME}/TUTORIALS/*.m \ 38 | ${DIRNAME}/*.pgm 39 | 40 | echo "G'zipping ${DIRNAME}/${TARFILE} ..." 41 | 42 | gzip ${DIRNAME}/$TARFILE 43 | gls -l "${DIRNAME}/$TARFILE.gz" 44 | 45 | popd 46 | 47 | echo "Done. Now:" 48 | echo " cd ${BASENAME}/${DIRNAME}" 49 | echo " scp ${TARFILE}.gz hopf:/Library/WebServer/Documents-www/ftp/eero/" 50 | echo " cp README /users/eero/html_public/matlabPyrTools.README" 51 | echo " cp ChangeLog /users/eero/html_public/matlabPyrTools.ChangeLog" 52 | echo " cp Contents.m /users/eero/html_public/matlabPyrTools-Contents.m" 53 | echo "" 54 | echo " Finally, mark as updated in ~lcv/html_public/software.html" 55 | echo "" 56 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/maxPyrHt.m: -------------------------------------------------------------------------------- 1 | % HEIGHT = maxPyrHt(IMSIZE, FILTSIZE) 2 | % 3 | % Compute maximum pyramid height for given image and filter sizes. 4 | % Specifically: the number of corrDn operations that can be sequentially 5 | % performed when subsampling by a factor of 2. 6 | 7 | % Eero Simoncelli, 6/96. 8 | 9 | function height = maxPyrHt(imsz, filtsz) 10 | 11 | imsz = imsz(:); 12 | filtsz = filtsz(:); 13 | 14 | if any(imsz == 1) % 1D image 15 | imsz = prod(imsz); 16 | filtsz = prod(filtsz); 17 | elseif any(filtsz == 1) % 2D image, 1D filter 18 | filtsz = [filtsz(1); filtsz(1)]; 19 | end 20 | 21 | if any(imsz < filtsz) 22 | height = 0; 23 | else 24 | height = 1 + maxPyrHt( floor(imsz/2), filtsz ); 25 | end 26 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/mean2.m: -------------------------------------------------------------------------------- 1 | % M = MEAN2(MTX) 2 | % 3 | % Sample mean of a matrix. 4 | 5 | function res = mean2(mtx) 6 | 7 | res = mean(mean(mtx)); 8 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/mkAngle.m: -------------------------------------------------------------------------------- 1 | % IM = mkAngle(SIZE, PHASE, ORIGIN) 2 | % 3 | % Compute a matrix of dimension SIZE (a [Y X] 2-vector, or a scalar) 4 | % containing samples of the polar angle (in radians, CW from the 5 | % X-axis, ranging from -pi to pi), relative to angle PHASE (default = 6 | % 0), about ORIGIN pixel (default = (size+1)/2). 7 | 8 | % Eero Simoncelli, 6/96. 9 | 10 | function [res] = mkAngle(sz, phase, origin) 11 | 12 | sz = sz(:); 13 | if (size(sz,1) == 1) 14 | sz = [sz,sz]; 15 | end 16 | 17 | % ----------------------------------------------------------------- 18 | % OPTIONAL args: 19 | 20 | if (exist('origin') ~= 1) 21 | origin = (sz+1)/2; 22 | end 23 | 24 | % ----------------------------------------------------------------- 25 | 26 | [xramp,yramp] = meshgrid( [1:sz(2)]-origin(2), [1:sz(1)]-origin(1) ); 27 | 28 | res = atan2(yramp,xramp); 29 | 30 | if (exist('phase') == 1) 31 | res = mod(res+(pi-phase),2*pi)-pi; 32 | end 33 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/mkAngularSine.m: -------------------------------------------------------------------------------- 1 | % IM = mkAngularSine(SIZE, HARMONIC, AMPL, PHASE, ORIGIN) 2 | % 3 | % Make an angular sinusoidal image: 4 | % AMPL * sin( HARMONIC*theta + PHASE), 5 | % where theta is the angle about the origin. 6 | % SIZE specifies the matrix size, as for zeros(). 7 | % AMPL (default = 1) and PHASE (default = 0) are optional. 8 | 9 | % Eero Simoncelli, 2/97. 10 | 11 | function [res] = mkAngularSine(sz, harmonic, ampl, ph, origin) 12 | 13 | sz = sz(:); 14 | if (size(sz,1) == 1) 15 | sz = [sz,sz]; 16 | end 17 | 18 | mxsz = max(sz(1),sz(2)); 19 | 20 | %------------------------------------------------------------ 21 | %% OPTIONAL ARGS: 22 | 23 | if (exist('harmonic') ~= 1) 24 | harmonic = 1; 25 | end 26 | 27 | if (exist('ampl') ~= 1) 28 | ampl = 1; 29 | end 30 | 31 | if (exist('ph') ~= 1) 32 | ph = 0; 33 | end 34 | 35 | if (exist('origin') ~= 1) 36 | origin = (sz+1)/2; 37 | end 38 | 39 | %------------------------------------------------------------ 40 | 41 | res = ampl * sin(harmonic*mkAngle(sz,ph,origin) + ph); 42 | 43 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/mkDisc.m: -------------------------------------------------------------------------------- 1 | % IM = mkDisc(SIZE, RADIUS, ORIGIN, TWIDTH, VALS) 2 | % 3 | % Make a "disk" image. SIZE specifies the matrix size, as for 4 | % zeros(). RADIUS (default = min(size)/4) specifies the radius of 5 | % the disk. ORIGIN (default = (size+1)/2) specifies the 6 | % location of the disk center. TWIDTH (in pixels, default = 2) 7 | % specifies the width over which a soft threshold transition is made. 8 | % VALS (default = [0,1]) should be a 2-vector containing the 9 | % intensity value inside and outside the disk. 10 | 11 | % Eero Simoncelli, 6/96. 12 | 13 | function [res] = mkDisc(sz, rad, origin, twidth, vals) 14 | 15 | if (nargin < 1) 16 | error('Must pass at least a size argument'); 17 | end 18 | 19 | sz = sz(:); 20 | if (size(sz,1) == 1) 21 | sz = [sz sz]; 22 | end 23 | 24 | %------------------------------------------------------------ 25 | % OPTIONAL ARGS: 26 | 27 | if (exist('rad') ~= 1) 28 | rad = min(sz(1),sz(2))/4; 29 | end 30 | 31 | if (exist('origin') ~= 1) 32 | origin = (sz+1)./2; 33 | end 34 | 35 | if (exist('twidth') ~= 1) 36 | twidth = 2; 37 | end 38 | 39 | if (exist('vals') ~= 1) 40 | vals = [1,0]; 41 | end 42 | 43 | %------------------------------------------------------------ 44 | 45 | res = mkR(sz,1,origin); 46 | 47 | if (abs(twidth) < realmin) 48 | res = vals(2) + (vals(1) - vals(2)) * (res <= rad); 49 | else 50 | [Xtbl,Ytbl] = rcosFn(twidth, rad, [vals(1), vals(2)]); 51 | res = pointOp(res, Ytbl, Xtbl(1), Xtbl(2)-Xtbl(1), 0); 52 | % 53 | % OLD interp1 VERSION: 54 | % res = res(:); 55 | % Xtbl(1) = min(res); 56 | % Xtbl(size(Xtbl,2)) = max(res); 57 | % res = reshape(interp1(Xtbl,Ytbl,res), sz(1), sz(2)); 58 | % 59 | end 60 | 61 | 62 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/mkFract.m: -------------------------------------------------------------------------------- 1 | % IM = mkFract(SIZE, FRACT_DIM) 2 | % 3 | % Make a matrix of dimensions SIZE (a [Y X] 2-vector, or a scalar) 4 | % containing fractal (pink) noise with power spectral density of the 5 | % form: 1/f^(5-2*FRACT_DIM). Image variance is normalized to 1.0. 6 | % FRACT_DIM defaults to 1.0 7 | 8 | % Eero Simoncelli, 6/96. 9 | 10 | %% TODO: Verify that this matches Mandelbrot defn of fractal dimension. 11 | %% Make this more efficient! 12 | 13 | function res = mkFract(dims, fract_dim) 14 | 15 | if (exist('fract_dim') ~= 1) 16 | fract_dim = 1.0; 17 | end 18 | 19 | res = randn(dims); 20 | fres = fft2(res); 21 | 22 | sz = size(res); 23 | ctr = ceil((sz+1)./2); 24 | 25 | shape = ifftshift(mkR(sz, -(2.5-fract_dim), ctr)); 26 | shape(1,1) = 1; %%DC term 27 | 28 | fres = shape .* fres; 29 | fres = ifft2(fres); 30 | 31 | if (max(max(abs(imag(fres)))) > 1e-10) 32 | error('Symmetry error in creating fractal'); 33 | else 34 | res = real(fres); 35 | res = res / sqrt(var2(res)); 36 | end 37 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/mkGaussian.m: -------------------------------------------------------------------------------- 1 | % IM = mkGaussian(SIZE, COVARIANCE, MEAN, AMPLITUDE) 2 | % 3 | % Compute a matrix with dimensions SIZE (a [Y X] 2-vector, or a 4 | % scalar) containing a Gaussian function, centered at pixel position 5 | % specified by MEAN (default = (size+1)/2), with given COVARIANCE (can 6 | % be a scalar, 2-vector, or 2x2 matrix. Default = (min(size)/6)^2), 7 | % and AMPLITUDE. AMPLITUDE='norm' (default) will produce a 8 | % probability-normalized function. All but the first argument are 9 | % optional. 10 | 11 | % Eero Simoncelli, 6/96. 12 | 13 | function [res] = mkGaussian(sz, cov, mn, ampl) 14 | 15 | sz = sz(:); 16 | if (size(sz,1) == 1) 17 | sz = [sz,sz]; 18 | end 19 | 20 | %------------------------------------------------------------ 21 | %% OPTIONAL ARGS: 22 | 23 | if (exist('cov') ~= 1) 24 | cov = (min(sz(1),sz(2))/6)^2; 25 | end 26 | 27 | if ( (exist('mn') ~= 1) | isempty(mn) ) 28 | mn = (sz+1)/2; 29 | else 30 | mn = mn(:); 31 | if (size(mn,1) == 1) 32 | mn = [mn, mn]; 33 | end 34 | end 35 | 36 | if (exist('ampl') ~= 1) 37 | ampl = 'norm'; 38 | end 39 | 40 | %------------------------------------------------------------ 41 | 42 | [xramp,yramp] = meshgrid([1:sz(2)]-mn(2),[1:sz(1)]-mn(1)); 43 | 44 | if (sum(size(cov)) == 2) % scalar 45 | if (strcmp(ampl,'norm')) 46 | ampl = 1/(2*pi*cov(1)); 47 | end 48 | e = (xramp.^2 + yramp.^2)/(-2 * cov); 49 | elseif (sum(size(cov)) == 3) % a 2-vector 50 | if (strcmp(ampl,'norm')) 51 | ampl = 1/(2*pi*sqrt(cov(1)*cov(2))); 52 | end 53 | e = xramp.^2/(-2 * cov(2)) + yramp.^2/(-2 * cov(1)); 54 | else 55 | if (strcmp(ampl,'norm')) 56 | ampl = 1/(2*pi*sqrt(det(cov))); 57 | end 58 | cov = -inv(cov)/2; 59 | e = cov(2,2)*xramp.^2 + (cov(1,2)+cov(2,1))*(xramp.*yramp) ... 60 | + cov(1,1)*yramp.^2; 61 | end 62 | 63 | res = ampl .* exp(e); 64 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/mkImpulse.m: -------------------------------------------------------------------------------- 1 | % IM = mkImpulse(SIZE, ORIGIN, AMPLITUDE) 2 | % 3 | % Compute a matrix of dimension SIZE (a [Y X] 2-vector, or a scalar) 4 | % containing a single non-zero entry, at position ORIGIN (defaults to 5 | % ceil(size/2)), of value AMPLITUDE (defaults to 1). 6 | 7 | % Eero Simoncelli, 6/96. 8 | 9 | function [res] = mkImpulse(sz, origin, amplitude) 10 | 11 | sz = sz(:)'; 12 | if (size(sz,2) == 1) 13 | sz = [sz sz]; 14 | end 15 | 16 | if (exist('origin') ~= 1) 17 | origin = ceil(sz/2); 18 | end 19 | 20 | if (exist('amplitude') ~= 1) 21 | amplitude = 1; 22 | end 23 | 24 | res = zeros(sz); 25 | res(origin(1),origin(2)) = amplitude; 26 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/mkR.m: -------------------------------------------------------------------------------- 1 | % IM = mkR(SIZE, EXPT, ORIGIN) 2 | % 3 | % Compute a matrix of dimension SIZE (a [Y X] 2-vector, or a scalar) 4 | % containing samples of a radial ramp function, raised to power EXPT 5 | % (default = 1), with given ORIGIN (default = (size+1)/2, [1 1] = 6 | % upper left). All but the first argument are optional. 7 | 8 | % Eero Simoncelli, 6/96. 9 | 10 | function [res] = mkR(sz, expt, origin) 11 | 12 | sz = sz(:); 13 | if (size(sz,1) == 1) 14 | sz = [sz,sz]; 15 | end 16 | 17 | % ----------------------------------------------------------------- 18 | % OPTIONAL args: 19 | 20 | if (exist('expt') ~= 1) 21 | expt = 1; 22 | end 23 | 24 | if (exist('origin') ~= 1) 25 | origin = (sz+1)/2; 26 | end 27 | 28 | % ----------------------------------------------------------------- 29 | 30 | [xramp,yramp] = meshgrid( [1:sz(2)]-origin(2), [1:sz(1)]-origin(1) ); 31 | 32 | res = (xramp.^2 + yramp.^2).^(expt/2); 33 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/mkRamp.m: -------------------------------------------------------------------------------- 1 | % IM = mkRamp(SIZE, DIRECTION, SLOPE, INTERCEPT, ORIGIN) 2 | % 3 | % Compute a matrix of dimension SIZE (a [Y X] 2-vector, or a scalar) 4 | % containing samples of a ramp function, with given gradient DIRECTION 5 | % (radians, CW from X-axis, default = 0), SLOPE (per pixel, default = 6 | % 1), and a value of INTERCEPT (default = 0) at the ORIGIN (default = 7 | % (size+1)/2, [1 1] = upper left). All but the first argument are 8 | % optional. 9 | 10 | % Eero Simoncelli, 6/96. 2/97: adjusted coordinate system. 11 | 12 | function [res] = mkRamp(sz, dir, slope, intercept, origin) 13 | 14 | sz = sz(:); 15 | if (size(sz,1) == 1) 16 | sz = [sz,sz]; 17 | end 18 | 19 | % ----------------------------------------------------------------- 20 | % OPTIONAL args: 21 | 22 | if (exist('dir') ~= 1) 23 | dir = 0; 24 | end 25 | 26 | if (exist('slope') ~= 1) 27 | slope = 1; 28 | end 29 | 30 | if (exist('intercept') ~= 1) 31 | intercept = 0; 32 | end 33 | 34 | if (exist('origin') ~= 1) 35 | origin = (sz+1)/2; 36 | end 37 | 38 | % ----------------------------------------------------------------- 39 | 40 | xinc = slope*cos(dir); 41 | yinc = slope*sin(dir); 42 | 43 | [xramp,yramp] = meshgrid( xinc*([1:sz(2)]-origin(2)), ... 44 | yinc*([1:sz(1)]-origin(1)) ); 45 | 46 | res = intercept + xramp + yramp; 47 | 48 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/mkSine.m: -------------------------------------------------------------------------------- 1 | % IM = mkSine(SIZE, PERIOD, DIRECTION, AMPLITUDE, PHASE, ORIGIN) 2 | % or 3 | % IM = mkSine(SIZE, FREQ, AMPLITUDE, PHASE, ORIGIN) 4 | % 5 | % Compute a matrix of dimension SIZE (a [Y X] 2-vector, or a scalar) 6 | % containing samples of a 2D sinusoid, with given PERIOD (in pixels), 7 | % DIRECTION (radians, CW from X-axis, default = 0), AMPLITUDE (default 8 | % = 1), and PHASE (radians, relative to ORIGIN, default = 0). ORIGIN 9 | % defaults to the center of the image. 10 | % 11 | % In the second form, FREQ is a 2-vector of frequencies (radians/pixel). 12 | 13 | % Eero Simoncelli, 6/96. 14 | 15 | function [res] = mkSine(sz, per_freq, dir_amp, amp_phase, phase_orig, orig) 16 | 17 | %------------------------------------------------------------ 18 | %% OPTIONAL ARGS: 19 | 20 | if (prod(size(per_freq)) == 2) 21 | frequency = norm(per_freq); 22 | direction = atan2(per_freq(1),per_freq(2)); 23 | if (exist('dir_amp') == 1) 24 | amplitude = dir_amp; 25 | else 26 | amplitude = 1; 27 | end 28 | if (exist('amp_phase') == 1) 29 | phase = amp_phase; 30 | else 31 | phase = 0; 32 | end 33 | if (exist('phase_orig') == 1) 34 | origin = phase_orig; 35 | end 36 | if (exist('orig') == 1) 37 | error('Too many arguments for (second form) of mkSine'); 38 | end 39 | else 40 | frequency = 2*pi/per_freq; 41 | if (exist('dir_amp') == 1) 42 | direction = dir_amp; 43 | else 44 | direction = 0; 45 | end 46 | if (exist('amp_phase') == 1) 47 | amplitude = amp_phase; 48 | else 49 | amplitude = 1; 50 | end 51 | if (exist('phase_orig') == 1) 52 | phase = phase_orig; 53 | else 54 | phase = 0; 55 | end 56 | if (exist('orig') == 1) 57 | origin = orig; 58 | end 59 | end 60 | 61 | %------------------------------------------------------------ 62 | 63 | if (exist('origin') == 1) 64 | res = amplitude*sin(mkRamp(sz, direction, frequency, phase, origin)); 65 | else 66 | res = amplitude*sin(mkRamp(sz, direction, frequency, phase)); 67 | end 68 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/mkZonePlate.m: -------------------------------------------------------------------------------- 1 | % IM = mkZonePlate(SIZE, AMPL, PHASE) 2 | % 3 | % Make a "zone plate" image: 4 | % AMPL * cos( r^2 + PHASE) 5 | % SIZE specifies the matrix size, as for zeros(). 6 | % AMPL (default = 1) and PHASE (default = 0) are optional. 7 | 8 | % Eero Simoncelli, 6/96. 9 | 10 | function [res] = mkZonePlate(sz, ampl, ph) 11 | 12 | sz = sz(:); 13 | if (size(sz,1) == 1) 14 | sz = [sz,sz]; 15 | end 16 | 17 | mxsz = max(sz(1),sz(2)); 18 | 19 | %------------------------------------------------------------ 20 | %% OPTIONAL ARGS: 21 | 22 | if (exist('ampl') ~= 1) 23 | ampl = 1; 24 | end 25 | 26 | if (exist('ph') ~= 1) 27 | ph = 0; 28 | end 29 | 30 | %------------------------------------------------------------ 31 | 32 | res = ampl * cos( (pi/mxsz) * mkR(sz,2) + ph ); 33 | 34 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/modulateFlip.m: -------------------------------------------------------------------------------- 1 | % [HFILT] = modulateFlipShift(LFILT) 2 | % 3 | % QMF/Wavelet highpass filter construction: modulate by (-1)^n, 4 | % reverse order (and shift by one, which is handled by the convolution 5 | % routines). This is an extension of the original definition of QMF's 6 | % (e.g., see Simoncelli90). 7 | 8 | % Eero Simoncelli, 7/96. 9 | 10 | function [hfilt] = modulateFlipShift(lfilt) 11 | 12 | lfilt = lfilt(:); 13 | 14 | sz = size(lfilt,1); 15 | sz2 = ceil(sz/2); 16 | 17 | ind = [sz:-1:1]'; 18 | 19 | hfilt = lfilt(ind) .* (-1).^(ind-sz2); 20 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/nextFig.m: -------------------------------------------------------------------------------- 1 | % nextFig (MAXFIGS, SKIP) 2 | % 3 | % Make figure number mod((GCF+SKIP), MAXFIGS) the current figure. 4 | % MAXFIGS is optional, and defaults to 2. 5 | % SKIP is optional, and defaults to 1. 6 | 7 | % Eero Simoncelli, 2/97. 8 | 9 | function nextFig(maxfigs, skip) 10 | 11 | if (exist('maxfigs') ~= 1) 12 | maxfigs = 2; 13 | end 14 | 15 | if (exist('skip') ~= 1) 16 | skip = 1; 17 | end 18 | 19 | figure(1+mod(gcf-1+skip,maxfigs)); 20 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/pgmRead.m: -------------------------------------------------------------------------------- 1 | % IM = pgmRead( FILENAME ) 2 | % 3 | % Load a pgm image into a MatLab matrix. 4 | % This format is accessible from the XV image browsing utility. 5 | % Only works for 8bit gray images (raw or ascii) 6 | 7 | % Hany Farid, Spring '96. Modified by Eero Simoncelli, 6/96. 8 | 9 | function im = pgmRead( fname ); 10 | 11 | [fid,msg] = fopen( fname, 'r' ); 12 | 13 | if (fid == -1) 14 | error(msg); 15 | end 16 | 17 | %%% First line contains ID string: 18 | %%% "P1" = ascii bitmap, "P2" = ascii greymap, 19 | %%% "P3" = ascii pixmap, "P4" = raw bitmap, 20 | %%% "P5" = raw greymap, "P6" = raw pixmap 21 | TheLine = fgetl(fid); 22 | format = TheLine; 23 | 24 | if ~((format(1:2) == 'P2') | (format(1:2) == 'P5')) 25 | error('PGM file must be of type P2 or P5'); 26 | end 27 | 28 | %%% Any number of comment lines 29 | TheLine = fgetl(fid); 30 | while TheLine(1) == '#' 31 | TheLine = fgetl(fid); 32 | end 33 | 34 | %%% dimensions 35 | sz = sscanf(TheLine,'%d',2); 36 | xdim = sz(1); 37 | ydim = sz(2); 38 | sz = xdim * ydim; 39 | 40 | %%% Maximum pixel value 41 | TheLine = fgetl(fid); 42 | maxval = sscanf(TheLine, '%d',1); 43 | 44 | %%im = zeros(dim,1); 45 | if (format(2) == '2') 46 | [im,count] = fscanf(fid,'%d',sz); 47 | else 48 | [im,count] = fread(fid,sz,'uchar'); 49 | end 50 | 51 | fclose(fid); 52 | 53 | if (count == sz) 54 | im = reshape( im, xdim, ydim )'; 55 | else 56 | fprintf(1,'Warning: File ended early!'); 57 | im = reshape( [im ; zeros(sz-count,1)], xdim, ydim)'; 58 | end 59 | 60 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/pixelAxes.m: -------------------------------------------------------------------------------- 1 | % [ZOOM] = pixelAxes(DIMS, ZOOM) 2 | % 3 | % Set the axes of the current plot to cover a multiple of DIMS pixels, 4 | % thereby eliminating screen aliasing artifacts when displaying an 5 | % image of size DIMS. 6 | % 7 | % ZOOM (optional, default='same') expresses the desired number of 8 | % samples displayed per screen pixel. It should be a scalar, which 9 | % will be rounded to the nearest integer, or 1 over an integer. It 10 | % may also be the string 'same' or 'auto', in which case the value is chosen so 11 | % as to produce an image closest in size to the currently displayed 12 | % image. It may also be the string 'full', in which case the image is 13 | % made as large as possible while still fitting in the window. 14 | 15 | % Eero Simoncelli, 2/97. 16 | 17 | function [zoom] = pixelAxes(dims, zoom) 18 | 19 | %------------------------------------------------------------ 20 | %% OPTIONAL ARGS: 21 | 22 | if (exist('zoom') ~= 1) 23 | zoom = 'same'; 24 | end 25 | 26 | %% Reverse dimension order, since Figure Positions reported as (x,y). 27 | dims = dims(2:-1:1); 28 | 29 | %% Use MatLab's axis function to force square pixels, etc: 30 | axis('image'); 31 | ax = gca; 32 | 33 | oldunits = get(ax,'Units'); 34 | 35 | if strcmp(zoom,'full'); 36 | set(ax,'Units','normalized'); 37 | set(ax,'Position',[0 0 1 1]); 38 | zoom = 'same'; 39 | end 40 | 41 | set(ax,'Units','pixels'); 42 | pos = get(ax,'Position'); 43 | ctr = pos(1:2)+pos(3:4)/2; 44 | 45 | if (strcmp(zoom,'same') | strcmp(zoom,'auto')) 46 | %% HACK: enlarge slightly so that floor doesn't round down 47 | zoom = min( pos(3:4) ./ (dims - 1) ); 48 | elseif isstr(zoom) 49 | error(sprintf('Bad ZOOM argument: %s',zoom)); 50 | end 51 | 52 | %% Force zoom value to be an integer, or inverse integer. 53 | if (zoom < 0.75) 54 | zoom = 1/ceil(1/zoom); 55 | %% Round upward, subtracting 0.5 to avoid floating point errors. 56 | newsz = ceil(zoom*(dims-0.5)); 57 | else 58 | zoom = floor(zoom + 0.001); % Avoid floating pt errors 59 | if (zoom < 1.5) % zoom=1 60 | zoom = 1; 61 | newsz = dims + 0.5; 62 | else 63 | newsz = zoom*(dims-1) + mod(zoom,2); 64 | end 65 | end 66 | 67 | set(ax,'Position', [floor(ctr-newsz/2)+0.5, newsz] ) 68 | 69 | % Restore units 70 | set(ax,'Units',oldunits); 71 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/pointOp.m: -------------------------------------------------------------------------------- 1 | % RES = pointOp(IM, LUT, ORIGIN, INCREMENT, WARNINGS) 2 | % 3 | % Apply a point operation, specified by lookup table LUT, to image IM. 4 | % LUT must be a row or column vector, and is assumed to contain 5 | % (equi-spaced) samples of the function. ORIGIN specifies the 6 | % abscissa associated with the first sample, and INCREMENT specifies the 7 | % spacing between samples. Between-sample values are estimated via 8 | % linear interpolation. If WARNINGS is non-zero, the function prints 9 | % a warning whenever the lookup table is extrapolated. 10 | % 11 | % This function is much faster than MatLab's interp1, and allows 12 | % extrapolation beyond the lookup table domain. The drawbacks are 13 | % that the lookup table must be equi-spaced, and the interpolation is 14 | % linear. 15 | 16 | % Eero Simoncelli, 8/96. 17 | 18 | function res = pointOp(im, lut, origin, increment, warnings) 19 | 20 | %% NOTE: THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD) 21 | 22 | % fprintf(1,'WARNING: You should compile the MEX version of "pointOp.c",\n found in the MEX subdirectory of matlabPyrTools, and put it in your matlab path. It is MUCH faster.\n'); 23 | 24 | X = origin + increment*[0:size(lut(:),1)-1]; 25 | Y = lut(:); 26 | 27 | res = reshape(interp1(X, Y, im(:), 'linear', 'extrap'),size(im)); 28 | 29 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/pointOp.mexa64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/pointOp.mexa64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/pointOp.mexglx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/pointOp.mexglx -------------------------------------------------------------------------------- /utils/matlabPyrTools/pointOp.mexmac: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/pointOp.mexmac -------------------------------------------------------------------------------- /utils/matlabPyrTools/pointOp.mexmaci64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/pointOp.mexmaci64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/pointOp.mexw32: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/pointOp.mexw32 -------------------------------------------------------------------------------- /utils/matlabPyrTools/pwd2path.m: -------------------------------------------------------------------------------- 1 | % PWD2PATH() 2 | % 3 | % add current working directory (pwd) to path. 4 | 5 | P = path; 6 | path(pwd,P); 7 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/pyrBand.m: -------------------------------------------------------------------------------- 1 | % RES = pyrBand(PYR, INDICES, BAND_NUM) 2 | % 3 | % Access a subband from a pyramid (gaussian, laplacian, QMF/wavelet, 4 | % or steerable). Subbands are numbered consecutively, from finest 5 | % (highest spatial frequency) to coarsest (lowest spatial frequency). 6 | 7 | % Eero Simoncelli, 6/96. 8 | 9 | function res = pyrBand(pyr, pind, band) 10 | 11 | res = reshape( pyr(pyrBandIndices(pind,band)), pind(band,1), pind(band,2) ); 12 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/pyrBandIndices.m: -------------------------------------------------------------------------------- 1 | % RES = pyrBandIndices(INDICES, BAND_NUM) 2 | % 3 | % Return indices for accessing a subband from a pyramid 4 | % (gaussian, laplacian, QMF/wavelet, steerable). 5 | 6 | % Eero Simoncelli, 6/96. 7 | 8 | function indices = pyrBandIndices(pind,band) 9 | 10 | if ((band > size(pind,1)) | (band < 1)) 11 | error(sprintf('BAND_NUM must be between 1 and number of pyramid bands (%d).', ... 12 | size(pind,1))); 13 | end 14 | 15 | if (size(pind,2) ~= 2) 16 | error('INDICES must be an Nx2 matrix indicating the size of the pyramid subbands'); 17 | end 18 | 19 | ind = 1; 20 | for l=1:band-1 21 | ind = ind + prod(pind(l,:)); 22 | end 23 | 24 | indices = ind:ind+prod(pind(band,:))-1; 25 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/pyrLow.m: -------------------------------------------------------------------------------- 1 | % RES = pyrLow(PYR, INDICES) 2 | % 3 | % Access the lowpass subband from a pyramid 4 | % (gaussian, laplacian, QMF/wavelet, steerable). 5 | 6 | % Eero Simoncelli, 6/96. 7 | 8 | function res = pyrLow(pyr,pind) 9 | 10 | band = size(pind,1); 11 | 12 | res = reshape( pyr(pyrBandIndices(pind,band)), pind(band,1), pind(band,2) ); 13 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/pyrTools.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/pyrTools.pdf -------------------------------------------------------------------------------- /utils/matlabPyrTools/range2.m: -------------------------------------------------------------------------------- 1 | % [MIN, MAX] = range2(MTX) 2 | % 3 | % Compute minimum and maximum values of MTX, returning them as a 2-vector. 4 | 5 | % Eero Simoncelli, 3/97. 6 | 7 | function [mn, mx] = range2(mtx) 8 | 9 | %% NOTE: THIS CODE IS NOT ACTUALLY USED! (MEX FILE IS CALLED INSTEAD) 10 | 11 | fprintf(1,'WARNING: You should compile the MEX version of "range2.c",\n found in the MEX subdirectory of matlabPyrTools, and put it in your matlab path. It is MUCH faster.\n'); 12 | 13 | if (~isreal(mtx)) 14 | error('MTX must be real-valued'); 15 | end 16 | 17 | mn = min(min(mtx)); 18 | mx = max(max(mtx)); 19 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/range2.mexa64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/range2.mexa64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/range2.mexglx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/range2.mexglx -------------------------------------------------------------------------------- /utils/matlabPyrTools/range2.mexmac: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/range2.mexmac -------------------------------------------------------------------------------- /utils/matlabPyrTools/range2.mexmaci64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/range2.mexmaci64 -------------------------------------------------------------------------------- /utils/matlabPyrTools/range2.mexw32: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/matlabPyrTools/range2.mexw32 -------------------------------------------------------------------------------- /utils/matlabPyrTools/rconv2.m: -------------------------------------------------------------------------------- 1 | % RES = RCONV2(MTX1, MTX2, CTR) 2 | % 3 | % Convolution of two matrices, with boundaries handled via reflection 4 | % about the edge pixels. Result will be of size of LARGER matrix. 5 | % 6 | % The origin of the smaller matrix is assumed to be its center. 7 | % For even dimensions, the origin is determined by the CTR (optional) 8 | % argument: 9 | % CTR origin 10 | % 0 DIM/2 (default) 11 | % 1 (DIM/2)+1 12 | 13 | % Eero Simoncelli, 6/96. 14 | 15 | function c = rconv2(a,b,ctr) 16 | 17 | if (exist('ctr') ~= 1) 18 | ctr = 0; 19 | end 20 | 21 | if (( size(a,1) >= size(b,1) ) & ( size(a,2) >= size(b,2) )) 22 | large = a; small = b; 23 | elseif (( size(a,1) <= size(b,1) ) & ( size(a,2) <= size(b,2) )) 24 | large = b; small = a; 25 | else 26 | error('one arg must be larger than the other in both dimensions!'); 27 | end 28 | 29 | ly = size(large,1); 30 | lx = size(large,2); 31 | sy = size(small,1); 32 | sx = size(small,2); 33 | 34 | %% These values are one less than the index of the small mtx that falls on 35 | %% the border pixel of the large matrix when computing the first 36 | %% convolution response sample: 37 | sy2 = floor((sy+ctr-1)/2); 38 | sx2 = floor((sx+ctr-1)/2); 39 | 40 | % pad with reflected copies 41 | clarge = [ 42 | large(sy-sy2:-1:2,sx-sx2:-1:2), large(sy-sy2:-1:2,:), ... 43 | large(sy-sy2:-1:2,lx-1:-1:lx-sx2); ... 44 | large(:,sx-sx2:-1:2), large, large(:,lx-1:-1:lx-sx2); ... 45 | large(ly-1:-1:ly-sy2,sx-sx2:-1:2), ... 46 | large(ly-1:-1:ly-sy2,:), ... 47 | large(ly-1:-1:ly-sy2,lx-1:-1:lx-sx2) ]; 48 | 49 | c = conv2(clarge,small,'valid'); 50 | 51 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/rcosFn.m: -------------------------------------------------------------------------------- 1 | % [X, Y] = rcosFn(WIDTH, POSITION, VALUES) 2 | % 3 | % Return a lookup table (suitable for use by INTERP1) 4 | % containing a "raised cosine" soft threshold function: 5 | % 6 | % Y = VALUES(1) + (VALUES(2)-VALUES(1)) * 7 | % cos^2( PI/2 * (X - POSITION + WIDTH)/WIDTH ) 8 | % 9 | % WIDTH is the width of the region over which the transition occurs 10 | % (default = 1). POSITION is the location of the center of the 11 | % threshold (default = 0). VALUES (default = [0,1]) specifies the 12 | % values to the left and right of the transition. 13 | 14 | % Eero Simoncelli, 7/96. 15 | 16 | function [X, Y] = rcosFn(width,position,values) 17 | 18 | %------------------------------------------------------------ 19 | % OPTIONAL ARGS: 20 | 21 | if (exist('width') ~= 1) 22 | width = 1; 23 | end 24 | 25 | if (exist('position') ~= 1) 26 | position = 0; 27 | end 28 | 29 | if (exist('values') ~= 1) 30 | values = [0,1]; 31 | end 32 | 33 | %------------------------------------------------------------ 34 | 35 | sz = 256; %% arbitrary! 36 | 37 | X = pi * [-sz-1:1] / (2*sz); 38 | 39 | Y = values(1) + (values(2)-values(1)) * cos(X).^2; 40 | 41 | % Make sure end values are repeated, for extrapolation... 42 | Y(1) = Y(2); 43 | Y(sz+3) = Y(sz+2); 44 | 45 | X = position + (2*width/pi) * (X + pi/4); 46 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/reconLpyr.m: -------------------------------------------------------------------------------- 1 | % RES = reconLpyr(PYR, INDICES, LEVS, FILT2, EDGES) 2 | % 3 | % Reconstruct image from Laplacian pyramid, as created by buildLpyr. 4 | % 5 | % PYR is a vector containing the N pyramid subbands, ordered from fine 6 | % to coarse. INDICES is an Nx2 matrix containing the sizes of 7 | % each subband. This is compatible with the MatLab Wavelet toolbox. 8 | % 9 | % LEVS (optional) should be a list of levels to include, or the string 10 | % 'all' (default). The finest scale is number 1. The lowpass band 11 | % corresponds to lpyrHt(INDICES)+1. 12 | % 13 | % FILT2 (optional) can be a string naming a standard filter (see 14 | % namedFilter), or a vector which will be used for (separable) 15 | % convolution. Default = 'binom5'. EDGES specifies edge-handling, 16 | % and defaults to 'reflect1' (see corrDn). 17 | 18 | % Eero Simoncelli, 6/96 19 | 20 | function res = reconLpyr(pyr, ind, levs, filt2, edges) 21 | 22 | if (nargin < 2) 23 | error('First two arguments (PYR, INDICES) are required'); 24 | end 25 | 26 | %%------------------------------------------------------------ 27 | %% DEFAULTS: 28 | 29 | if (exist('levs') ~= 1) 30 | levs = 'all'; 31 | end 32 | 33 | if (exist('filt2') ~= 1) 34 | filt2 = 'binom5'; 35 | end 36 | 37 | if (exist('edges') ~= 1) 38 | edges= 'reflect1'; 39 | end 40 | %%------------------------------------------------------------ 41 | 42 | maxLev = 1+lpyrHt(ind); 43 | if strcmp(levs,'all') 44 | levs = [1:maxLev]'; 45 | else 46 | if (any(levs > maxLev)) 47 | error(sprintf('Level numbers must be in the range [1, %d].', maxLev)); 48 | end 49 | levs = levs(:); 50 | end 51 | 52 | if isstr(filt2) 53 | filt2 = namedFilter(filt2); 54 | end 55 | 56 | filt2 = filt2(:); 57 | res_sz = ind(1,:); 58 | 59 | if any(levs > 1) 60 | 61 | int_sz = [ind(1,1), ind(2,2)]; 62 | 63 | nres = reconLpyr( pyr(prod(res_sz)+1:size(pyr,1)), ... 64 | ind(2:size(ind,1),:), levs-1, filt2, edges); 65 | 66 | if (res_sz(1) == 1) 67 | res = upConv(nres, filt2', edges, [1 2], [1 1], res_sz); 68 | elseif (res_sz(2) == 1) 69 | res = upConv(nres, filt2, edges, [2 1], [1 1], res_sz); 70 | else 71 | hi = upConv(nres, filt2, edges, [2 1], [1 1], int_sz); 72 | res = upConv(hi, filt2', edges, [1 2], [1 1], res_sz); 73 | end 74 | 75 | else 76 | 77 | res = zeros(res_sz); 78 | 79 | end 80 | 81 | if any(levs == 1) 82 | res = res + pyrBand(pyr,ind,1); 83 | end 84 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/reconSFpyrLevs.m: -------------------------------------------------------------------------------- 1 | % RESDFT = reconSFpyrLevs(PYR,INDICES,LOGRAD,XRCOS,YRCOS,ANGLE,NBANDS,LEVS,BANDS) 2 | % 3 | % Recursive function for reconstructing levels of a steerable pyramid 4 | % representation. This is called by reconSFpyr, and is not usually 5 | % called directly. 6 | 7 | % Eero Simoncelli, 5/97. 8 | 9 | function resdft = reconSFpyrLevs(pyr,pind,log_rad,Xrcos,Yrcos,angle,nbands,levs,bands); 10 | 11 | lo_ind = nbands+1; 12 | dims = pind(1,:); 13 | ctr = ceil((dims+0.5)/2); 14 | 15 | % log_rad = log_rad + 1; 16 | Xrcos = Xrcos - log2(2); % shift origin of lut by 1 octave. 17 | 18 | if any(levs > 1) 19 | 20 | lodims = ceil((dims-0.5)/2); 21 | loctr = ceil((lodims+0.5)/2); 22 | lostart = ctr-loctr+1; 23 | loend = lostart+lodims-1; 24 | nlog_rad = log_rad(lostart(1):loend(1),lostart(2):loend(2)); 25 | nangle = angle(lostart(1):loend(1),lostart(2):loend(2)); 26 | 27 | if (size(pind,1) > lo_ind) 28 | nresdft = reconSFpyrLevs( pyr(1+sum(prod(pind(1:lo_ind-1,:)')):size(pyr,1)),... 29 | pind(lo_ind:size(pind,1),:), ... 30 | nlog_rad, Xrcos, Yrcos, nangle, nbands,levs-1, bands); 31 | else 32 | nresdft = fftshift(fft2(pyrBand(pyr,pind,lo_ind))); 33 | end 34 | 35 | YIrcos = sqrt(abs(1.0 - Yrcos.^2)); 36 | lomask = pointOp(nlog_rad, YIrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0); 37 | 38 | resdft = zeros(dims); 39 | resdft(lostart(1):loend(1),lostart(2):loend(2)) = nresdft .* lomask; 40 | 41 | else 42 | 43 | resdft = zeros(dims); 44 | 45 | end 46 | 47 | 48 | if any(levs == 1) 49 | 50 | lutsize = 1024; 51 | Xcosn = pi*[-(2*lutsize+1):(lutsize+1)]/lutsize; % [-2*pi:pi] 52 | order = nbands-1; 53 | %% divide by sqrt(sum_(n=0)^(N-1) cos(pi*n/N)^(2(N-1)) ) 54 | const = (2^(2*order))*(factorial(order)^2)/(nbands*factorial(2*order)); 55 | Ycosn = sqrt(const) * (cos(Xcosn)).^order; 56 | himask = pointOp(log_rad, Yrcos, Xrcos(1), Xrcos(2)-Xrcos(1),0); 57 | 58 | ind = 1; 59 | for b = 1:nbands 60 | if any(bands == b) 61 | anglemask = pointOp(angle,Ycosn,Xcosn(1)+pi*(b-1)/nbands,Xcosn(2)-Xcosn(1)); 62 | band = reshape(pyr(ind:ind+prod(dims)-1), dims(1), dims(2)); 63 | banddft = fftshift(fft2(band)); 64 | resdft = resdft + (sqrt(-1))^(nbands-1) * banddft.*anglemask.*himask; 65 | end 66 | ind = ind + prod(dims); 67 | end 68 | end 69 | 70 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/reconSpyrLevs.m: -------------------------------------------------------------------------------- 1 | % RES = reconSpyrLevs(PYR,INDICES,LOFILT,BFILTS,EDGES,LEVS,BANDS) 2 | % 3 | % Recursive function for reconstructing levels of a steerable pyramid 4 | % representation. This is called by reconSpyr, and is not usually 5 | % called directly. 6 | 7 | % Eero Simoncelli, 6/96. 8 | 9 | function res = reconSpyrLevs(pyr,pind,lofilt,bfilts,edges,levs,bands); 10 | 11 | nbands = size(bfilts,2); 12 | lo_ind = nbands+1; 13 | res_sz = pind(1,:); 14 | 15 | % Assume square filters: 16 | bfiltsz = round(sqrt(size(bfilts,1))); 17 | 18 | if any(levs > 1) 19 | 20 | if (size(pind,1) > lo_ind) 21 | nres = reconSpyrLevs( pyr(1+sum(prod(pind(1:lo_ind-1,:)')):size(pyr,1)), ... 22 | pind(lo_ind:size(pind,1),:), ... 23 | lofilt, bfilts, edges, levs-1, bands); 24 | else 25 | nres = pyrBand(pyr,pind,lo_ind); % lowpass subband 26 | end 27 | 28 | res = upConv(nres, lofilt, edges, [2 2], [1 1], res_sz); 29 | 30 | else 31 | 32 | res = zeros(res_sz); 33 | 34 | end 35 | 36 | if any(levs == 1) 37 | ind = 1; 38 | for b = 1:nbands 39 | if any(bands == b) 40 | bfilt = reshape(bfilts(:,b), bfiltsz, bfiltsz); 41 | res = upConv(reshape(pyr(ind:ind+prod(res_sz)-1), res_sz(1), res_sz(2)), ... 42 | bfilt, edges, [1 1], [1 1], res_sz, res); 43 | end 44 | ind = ind + prod(res_sz); 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/setPyrBand.m: -------------------------------------------------------------------------------- 1 | % NEWPYR = setPyrBand(PYR, INDICES, NEWBAND, BAND_NUM) 2 | % 3 | % Insert an image (BAND) into a pyramid (gaussian, laplacian, QMF/wavelet, 4 | % or steerable). Subbands are numbered consecutively, from finest 5 | % (highest spatial frequency) to coarsest (lowest spatial frequency). 6 | 7 | % Eero Simoncelli, 1/03. 8 | 9 | function pyr = setPyrBand(pyr, pind, band, bandNum) 10 | 11 | %% Check: PIND a valid index matrix? 12 | if ( ~(ndims(pind) == 2) | ~(size(pind,2) == 2) | ~all(pind==round(pind)) ) 13 | pind 14 | error('pyrTools:badArg',... 15 | 'PIND argument is not an Nbands X 2 matrix of integers'); 16 | end 17 | 18 | %% Check: PIND consistent with size of PYR? 19 | if ( length(pyr) ~= sum(prod(pind,2)) ) 20 | error('pyrTools:badPyr',... 21 | 'Pyramid data vector length is inconsistent with index matrix PIND'); 22 | end 23 | 24 | %% Check: size of BAND consistent with desired BANDNUM? 25 | if (~all(size(band) == pind(bandNum,:))) 26 | size(band) 27 | pind(bandNum,:) 28 | error('pyrTools:badArg',... 29 | 'size of BAND to be inserted is inconsistent with BAND_NUM'); 30 | end 31 | 32 | pyr(pyrBandIndices(pind,bandNum)) = vectify(band); 33 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/shift.m: -------------------------------------------------------------------------------- 1 | % [RES] = shift(MTX, OFFSET) 2 | % 3 | % Circular shift 2D matrix samples by OFFSET (a [Y,X] 2-vector), 4 | % such that RES(POS) = MTX(POS-OFFSET). 5 | 6 | function res = shift(mtx, offset) 7 | 8 | dims = size(mtx); 9 | 10 | offset = mod(-offset,dims); 11 | 12 | res = [ mtx(offset(1)+1:dims(1), offset(2)+1:dims(2)), ... 13 | mtx(offset(1)+1:dims(1), 1:offset(2)); ... 14 | mtx(1:offset(1), offset(2)+1:dims(2)), ... 15 | mtx(1:offset(1), 1:offset(2)) ]; 16 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/skew2.m: -------------------------------------------------------------------------------- 1 | % S = SKEW2(MTX,MEAN,VAR) 2 | % 3 | % Sample skew (third moment divided by variance^3/2) of a matrix. 4 | % MEAN (optional) and VAR (optional) make the computation faster. 5 | 6 | function res = skew2(mtx, mn, v) 7 | 8 | if (exist('mn') ~= 1) 9 | mn = mean2(mtx); 10 | end 11 | 12 | if (exist('v') ~= 1) 13 | v = var2(mtx,mn); 14 | end 15 | 16 | if (isreal(mtx)) 17 | res = mean(mean((mtx-mn).^3)) / (v^(3/2)); 18 | else 19 | res = mean(mean(real(mtx-mn).^3)) / (real(v)^(3/2)) + ... 20 | i * mean(mean(imag(mtx-mn).^3)) / (imag(v)^(3/2)); 21 | end 22 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/spyrBand.m: -------------------------------------------------------------------------------- 1 | % [LEV,IND] = spyrBand(PYR,INDICES,LEVEL,BAND) 2 | % 3 | % Access a band from a steerable pyramid. 4 | % 5 | % LEVEL indicates the scale (finest = 1, coarsest = spyrHt(INDICES)). 6 | % 7 | % BAND (optional, default=1) indicates which subband 8 | % (1 = vertical, rest proceeding anti-clockwise). 9 | 10 | % Eero Simoncelli, 6/96. 11 | 12 | function res = spyrBand(pyr,pind,level,band) 13 | 14 | if (exist('level') ~= 1) 15 | level = 1; 16 | end 17 | 18 | if (exist('band') ~= 1) 19 | band = 1; 20 | end 21 | 22 | nbands = spyrNumBands(pind); 23 | if ((band > nbands) | (band < 1)) 24 | error(sprintf('Bad band number (%d) should be in range [1,%d].', band, nbands)); 25 | end 26 | 27 | maxLev = spyrHt(pind); 28 | if ((level > maxLev) | (level < 1)) 29 | error(sprintf('Bad level number (%d), should be in range [1,%d].', level, maxLev)); 30 | end 31 | 32 | firstband = 1 + band + nbands*(level-1); 33 | res = pyrBand(pyr, pind, firstband); 34 | 35 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/spyrHigh.m: -------------------------------------------------------------------------------- 1 | % RES = spyrHigh(PYR, INDICES) 2 | % 3 | % Access the highpass residual band from a steerable pyramid. 4 | 5 | % Eero Simoncelli, 6/96. 6 | 7 | function res = spyrHigh(pyr,pind) 8 | 9 | res = pyrBand(pyr, pind, 1); 10 | 11 | -------------------------------------------------------------------------------- /utils/matlabPyrTools/spyrHt.m: -------------------------------------------------------------------------------- 1 | % [HEIGHT] = spyrHt(INDICES) 2 | % 3 | % Compute height of steerable pyramid with given index matrix. 4 | 5 | % Eero Simoncelli, 6/96. 6 | 7 | function [ht] = spyrHt(pind) 8 | 9 | nbands = spyrNumBands(pind); 10 | 11 | % Don't count lowpass, or highpass residual bands 12 | if (size(pind,1) > 2) 13 | ht = (size(pind,1)-2)/nbands; 14 | else 15 | ht = 0; 16 | end 17 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/mcnExtraLayers-master.zip -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Samuel Albanie 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/README.md: -------------------------------------------------------------------------------- 1 | ## mcnExtraLayers 2 | 3 | This repo contains a collection of common MatConvNet functions and DagNN layers which are shared across a number of classification and object detection frameworks. 4 | 5 | ### Layers: 6 | 7 | * `vl_nnmax` - element-wise maximum across tensors 8 | * `vl_nnsum` - element-wise sum across tensors 9 | * `vl_nninterp` - a wrapper for bilinear interpolation 10 | * `vl_nnslice` - slicing along a given dimension 11 | * `vl_nnspatialsoftmax` - spatial application of the softmax operator 12 | * `vl_nnreshape` - tensor reshaping 13 | * `vl_nnchannelshuffle` - channel shuffling (introduced in [ShuffleNet](https://arxiv.org/abs/1707.01083)) 14 | * `vl_nnflatten` - flatten along a given dimension 15 | * `vl_nnglobalpool` - global pooling 16 | * `vl_nnsoftmaxt` - softmax along a given dimension 17 | * `vl_nncrop_wrapper` - autonn function wrapper for `vl_nncrop.m` 18 | * `vl_nnaxpy` - vector op `y <- a*x + y` (BLAS Level One style naming convention) 19 | * `vl_nngnorm` - group normalization (an alternative to batch norm) 20 | * `vl_nnhuberloss` - computation of the Huber (L1-smooth) loss 21 | * `vl_nneuclidenaloss` - computation of the Euclidean (L2-smooth) loss 22 | * `vl_nntukeyloss` - computation of Tukey's Biweight (robust) loss 23 | * `vl_nnsoftmaxceloss` - soft-target cross entropy loss (operates on logits) 24 | * `vl_nncaffepool` - "caffe-style" pooling (applies padding before pooling kernel) 25 | * `vl_nnl2norm` - l2 feature normalisation 26 | 27 | ### Dependencies 28 | 29 | mcnExtraLayers requires the following modules: 30 | 31 | * [autonn](https://github.com/vlfeat/autonn) - automatic differentiation 32 | 33 | ### Utilities 34 | 35 | The module also contains some additional utilities which may be useful during network training: 36 | 37 | * [findBestCheckpoint](https://github.com/albanie/mcnExtraLayers/blob/master/utils/findBestCheckpoint.m) - function to rank and prune network checkpoints saved during training (useful for saving space automatically at the end of a training run 38 | * [checkLearningParams](https://github.com/albanie/mcnExtraLayers/blob/master/utils/checkLearningParams.m) - compare mcn network against a caffe prototxt 39 | 40 | ### Install 41 | 42 | The module is easiest to install with the `vl_contrib` package manager: 43 | 44 | ``` 45 | vl_contrib('install', 'mcnExtraLayers') ; 46 | vl_contrib('setup', 'mcnExtraLayers') ; 47 | vl_contrib('test', 'mcnExtraLayers') ; % optional 48 | ``` 49 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/Axpy.m: -------------------------------------------------------------------------------- 1 | classdef Axpy < dagnn.Filter 2 | 3 | methods 4 | function outputs = forward(obj, inputs, params) %#ok 5 | outputs{1} = vl_nnaxpy(inputs{1}, inputs{2}, inputs{3}) ; 6 | end 7 | 8 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) %#ok 9 | derInputs = vl_nnaxpy(inputs{1}, inputs{2}, inputs{3}, derOutputs{1}) ; 10 | derParams = {} ; 11 | end 12 | 13 | function outputSizes = getOutputSizes(obj, inputSizes) %#ok 14 | % The output size of (A * X) + Y should be equal to 15 | % both X and Y 16 | assert(~any(isnan(inputSizes{2})), ... 17 | ['Found NaNs in the input variable dimensions. Was the ' ... 18 | 'dagnn.print() function called with input sizes?']) ; 19 | assert(all(inputSizes{2} == inputSizes{3}), 'mismatch') ; 20 | outputSizes{1} = inputSizes{2} ; 21 | end 22 | 23 | function obj = Axpy(varargin) 24 | obj.load(varargin) ; 25 | end 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/CaffePooling.m: -------------------------------------------------------------------------------- 1 | classdef CaffePooling < dagnn.Filter 2 | %CAFFEPOOLING - This layer implements Caffe-style pooling, which applies 3 | % the pooling kernel to the padding, as well as to the input (unlike matconvnet 4 | % which does not include the padding itself in the kernel computation). 5 | % To mimic this effect, we "pre-pad" the input using an empty convolution, then 6 | % pass to the standard pooling layer. 7 | 8 | properties 9 | method = 'max' 10 | poolSize = [1 1] 11 | opts = {'cuDNN'} 12 | end 13 | 14 | methods 15 | function outputs = forward(self, inputs, params) 16 | outputs{1} = vl_nncaffepool(inputs{1}, self.poolSize, ... 17 | 'pad', self.pad, ... 18 | 'method', self.method, ... 19 | 'stride', self.stride, ... 20 | 'extraArgs', self.opts) ; 21 | end 22 | 23 | function [derInputs, derParams] = backward(self, inputs, params, derOutputs) 24 | derInputs{1} = vl_nncaffepool(inputs{1}, self.poolSize, derOutputs{1}, ... 25 | 'pad', self.pad, ... 26 | 'method', self.method, ... 27 | 'stride', self.stride, ... 28 | 'extraArgs', self.opts) ; 29 | derParams = {} ; 30 | end 31 | 32 | function kernelSize = getKernelSize(obj) 33 | kernelSize = obj.poolSize ; 34 | end 35 | 36 | function outputSizes = getOutputSizes(obj, inputSizes) 37 | outputSizes = getOutputSizes@dagnn.Filter(obj, inputSizes) ; 38 | outputSizes{1}(3) = inputSizes{1}(3) ; 39 | end 40 | 41 | function obj = CaffePooling(varargin) 42 | obj.load(varargin) ; 43 | end 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/ChannelShuffle.m: -------------------------------------------------------------------------------- 1 | classdef ChannelShuffle < dagnn.Layer 2 | 3 | properties 4 | group = 1 5 | end 6 | 7 | methods 8 | function outputs = forward(obj, inputs, params) 9 | outputs{1} = vl_nnchannelshuffle(inputs{1}, obj.group) ; 10 | end 11 | 12 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 13 | derInputs{1} = vl_nnchannelshuffle(inputs{1}, obj.group, derOutputs{1}) ; 14 | derParams = {} ; 15 | end 16 | 17 | function outputSizes = getOutputSizes(obj, inputSizes) 18 | szi = inputSizes{1} ; 19 | szi = [szi, ones(1, 4 - numel(szi))] ; 20 | szo = [... 21 | szi(1:obj.firstAxis-1), ... 22 | prod(szi(obj.firstAxis:obj.axis)), ... 23 | szi(obj.axis+1:end)] ; 24 | outputSizes{1} = [ones(1,numel(szi)-numel(szo)), szo] ; 25 | end 26 | 27 | function obj = Flatten(varargin) 28 | obj.load(varargin{:}) ; 29 | obj.axis = obj.axis ; 30 | obj.firstAxis = obj.firstAxis ; 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/ClassPrecision.m: -------------------------------------------------------------------------------- 1 | classdef ClassPrecision < dagnn.Loss 2 | 3 | properties (Transient) 4 | numClasses = [] 5 | confusion = 0 6 | end 7 | 8 | methods 9 | function outputs = forward(obj, inputs, params) 10 | [~,predictions] = max(inputs{1}, [], 3) ; 11 | predictions = squeeze(gather(predictions)) ; 12 | labels = squeeze(gather(inputs{2})) ; 13 | 14 | numPreds = numel(predictions) ; 15 | obj.confusion = obj.confusion + ... 16 | accumarray([labels, predictions],1,[obj.numClasses obj.numClasses]) ; 17 | 18 | % compute various statistics of the confusion matrix 19 | % GT - rows, predicted - cols 20 | 21 | classPrec = zeros(1, obj.numClasses) ; 22 | for ii = 1:obj.numClasses 23 | tp_ = obj.confusion(ii,ii) ; 24 | fp_ = sum(obj.confusion(:,ii)) - tp_ ; 25 | classPrec(ii) = tp_ / (tp_ + fp_) ; 26 | end 27 | 28 | obj.average = classPrec ; 29 | obj.numAveraged = obj.numAveraged + numPreds ; 30 | outputs{1} = obj.average ; 31 | end 32 | 33 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 34 | derInputs{1} = [] ; 35 | derInputs{2} = [] ; 36 | derParams = {} ; 37 | end 38 | 39 | function reset(obj) 40 | obj.confusion = 0 ; 41 | obj.average = zeros(obj.numClasses, 1) ; 42 | obj.numAveraged = 0 ; 43 | end 44 | 45 | function obj = ClassPrecision(varargin) 46 | obj.load(varargin) ; 47 | end 48 | end 49 | end 50 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/ClassRecall.m: -------------------------------------------------------------------------------- 1 | classdef ClassRecall < dagnn.Loss 2 | 3 | properties (Transient) 4 | numClasses = [] 5 | confusion = 0 6 | end 7 | 8 | methods 9 | function outputs = forward(obj, inputs, params) 10 | [~,predictions] = max(inputs{1}, [], 3) ; 11 | predictions = squeeze(gather(predictions)) ; 12 | labels = squeeze(gather(inputs{2})) ; 13 | 14 | numPreds = numel(predictions) ; 15 | obj.confusion = obj.confusion + ... 16 | accumarray([labels, predictions],1,[obj.numClasses obj.numClasses]) ; 17 | 18 | % compute various statistics of the confusion matrix 19 | % GT - rows, predicted - cols 20 | classRec = zeros(1, obj.numClasses) ; 21 | for ii = 1:obj.numClasses 22 | tp_ = obj.confusion(ii,ii) ; 23 | fn_ = sum(obj.confusion(ii,:)) - tp_ ; 24 | classRec(ii) = tp_ / (tp_ + fn_) ; 25 | end 26 | 27 | obj.average = classRec ; 28 | obj.numAveraged = obj.numAveraged + numPreds ; 29 | outputs{1} = obj.average ; 30 | end 31 | 32 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 33 | derInputs{1} = [] ; 34 | derInputs{2} = [] ; 35 | derParams = {} ; 36 | end 37 | 38 | function reset(obj) 39 | obj.confusion = 0 ; 40 | obj.numAveraged = 0 ; 41 | obj.average = zeros(obj.numClasses, 1) ; 42 | end 43 | 44 | function obj = ClassRecall(varargin) 45 | obj.load(varargin) ; 46 | end 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/CosineSim.m: -------------------------------------------------------------------------------- 1 | classdef CosineSim < dagnn.Filter 2 | 3 | methods 4 | function outputs = forward(self, inputs, params) 5 | outputs{1} = vl_nncosinesim(inputs{1}, inputs{2}) ; 6 | end 7 | 8 | function [derInputs, derParams] = backward(self, inputs, params, derOutputs) 9 | derInputs{1} = vl_nncosinesim(inputs{1}, inputs{2}, derOutputs{1}) ; 10 | derParams = {} ; 11 | end 12 | 13 | function outputSizes = getOutputSizes(obj, inputSizes) 14 | outputSizes{1} = ones(1,4) ; 15 | outputSizes{1}(4) = inputSizes{1}(4) ; 16 | end 17 | 18 | function obj = CosineSim(varargin) 19 | obj.load(varargin) ; 20 | end 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/ErrorStats.m: -------------------------------------------------------------------------------- 1 | classdef ErrorStats < dagnn.Loss 2 | 3 | properties 4 | numClasses = [] 5 | end 6 | 7 | properties (Transient) 8 | confusion = 0 9 | classDist = 0 ; 10 | end 11 | 12 | methods 13 | function outputs = forward(obj, inputs, params) 14 | if isempty(obj.numClasses) % :( desperate times 15 | obj.numClasses = 8 ; obj.average = zeros(1, 8) ; 16 | end 17 | 18 | [~,predictions] = max(inputs{1}, [], 3) ; 19 | predictions = squeeze(gather(predictions)) ; 20 | labels = squeeze(gather(inputs{2})) ; 21 | obj.confusion = obj.confusion + ... 22 | accumarray([labels, predictions], 1, [obj.numClasses obj.numClasses]) ; 23 | classDist = sum(obj.confusion, 2)' ; 24 | classAccs = diag(obj.confusion)' ; 25 | outputs{1} = classAccs ; % perform normalisation later 26 | obj.accumulateAverage(classAccs, classDist) ; 27 | end 28 | 29 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 30 | derInputs{1} = [] ; 31 | derInputs{2} = [] ; 32 | derParams = {} ; 33 | end 34 | 35 | function accumulateAverage(obj, classAccs, classDist) 36 | if obj.ignoreAverage, return ; end 37 | n = obj.numAveraged ; 38 | m = max(n + classDist, 1e-5) ; 39 | classAvgs = bsxfun(@plus, n .* obj.average, classAccs) ./ m ; 40 | obj.average = classAvgs ; 41 | obj.classDist = obj.classDist + classDist ; 42 | obj.numAveraged = m ; 43 | end 44 | 45 | function reset(obj) 46 | obj.confusion = 0 ; 47 | obj.numAveraged = 0 ; 48 | obj.average = zeros(1, obj.numClasses) ; 49 | end 50 | 51 | function obj = ErrorStats(varargin) 52 | obj.load(varargin) ; 53 | end 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/EuclideanLoss.m: -------------------------------------------------------------------------------- 1 | classdef EuclideanLoss < dagnn.Loss 2 | 3 | methods 4 | function outputs = forward(obj, inputs, params) 5 | outputs{1} = vl_nneuclideanloss(inputs{1}, inputs{2}, ... 6 | 'instanceWeights', inputs{3}) ; 7 | n = obj.numAveraged ; 8 | m = n + size(inputs{1}, 4) ; 9 | obj.average = (n * obj.average + gather(outputs{1})) / m ; 10 | obj.numAveraged = m ; 11 | end 12 | 13 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 14 | derInputs{1} = vl_nneuclideanloss(inputs{1}, inputs{2}, derOutputs{1}, ... 15 | 'instanceWeights', inputs{3}) ; 16 | derInputs{2} = [] ; 17 | derInputs{3} = [] ; 18 | derParams = {} ; 19 | end 20 | 21 | function obj = EuclideanLoss(varargin) 22 | obj.load(varargin) ; 23 | end 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/Flatten.m: -------------------------------------------------------------------------------- 1 | classdef Flatten < dagnn.Layer 2 | % The Flatten layer reshapes the input tensor as follows. If 3 | % the shape of the input is [d1 d2 d3 ... dm], then shape of the output 4 | % is [1, ..., 1, d1, ..., d_{a-1}, da * ... * db, d_{b+1}, ..., dm] 5 | % where a and b are, respectively, the first and last flattened axis. 6 | properties 7 | firstAxis = 1 8 | axis = 3 9 | end 10 | 11 | methods 12 | function outputs = forward(obj, inputs, params) 13 | outputs{1} = vl_nnflatten(inputs{1}, obj.axis) ; 14 | end 15 | 16 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 17 | derInputs{1} = vl_nnflatten(inputs{1}, obj.axis, derOutputs{1}) ; 18 | derParams = {} ; 19 | end 20 | 21 | function outputSizes = getOutputSizes(obj, inputSizes) 22 | szi = inputSizes{1} ; 23 | szi = [szi, ones(1, 4 - numel(szi))] ; 24 | szo = [... 25 | szi(1:obj.firstAxis-1), ... 26 | prod(szi(obj.firstAxis:obj.axis)), ... 27 | szi(obj.axis+1:end)] ; 28 | outputSizes{1} = [ones(1,numel(szi)-numel(szo)), szo] ; 29 | end 30 | 31 | function obj = Flatten(varargin) 32 | obj.load(varargin{:}) ; 33 | obj.axis = obj.axis ; 34 | obj.firstAxis = obj.firstAxis ; 35 | end 36 | end 37 | end 38 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/GlobalPooling.m: -------------------------------------------------------------------------------- 1 | classdef GlobalPooling < dagnn.Filter 2 | properties 3 | method = 'avg' 4 | end 5 | 6 | methods 7 | function outputs = forward(obj, inputs, params) %#ok 8 | outputs{1} = vl_nnglobalpool(inputs{1}, 'method', obj.method) ; 9 | end 10 | 11 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) %#ok 12 | derInputs{1} = vl_nnglobalpool(inputs{1}, derOutputs{1}, 'method', obj.method) ; 13 | derParams = {} ; 14 | end 15 | 16 | function outputSizes = getOutputSizes(obj, inputSizes) %#ok 17 | assert(~any(isnan(inputSizes{1})), ... 18 | ['Found NaNs in the input variable dimensions. Was the ' ... 19 | 'dagnn.print() function called with input sizes?']) ; 20 | outputSizes{1}(3:4) = inputSizes{1}(3:4) ; 21 | outputSizes{1}(1:2) = [1 1] ; % collapse spatial dims 22 | end 23 | 24 | function obj = GlobalPooling(varargin) 25 | obj.load(varargin) ; 26 | end 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/HuberLoss.m: -------------------------------------------------------------------------------- 1 | classdef HuberLoss < dagnn.Loss 2 | 3 | properties 4 | sigma = 1. 5 | end 6 | 7 | methods 8 | function outputs = forward(obj, inputs, params) 9 | outputs{1} = vl_nnhuberloss(inputs{1}, inputs{2}, ... 10 | 'instanceWeights', inputs{3}, ... 11 | obj.opts{:}) ; 12 | n = obj.numAveraged ; 13 | m = n + size(inputs{1}, 4) ; 14 | obj.average = (n * obj.average + gather(outputs{1})) / m ; 15 | obj.numAveraged = m ; 16 | end 17 | 18 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 19 | derInputs{1} = vl_nnhuberloss(inputs{1}, inputs{2}, derOutputs{1}, ... 20 | 'instanceWeights', inputs{3}, ... 21 | obj.opts{:}) ; 22 | derInputs{2} = [] ; 23 | derInputs{3} = [] ; 24 | derParams = {} ; 25 | end 26 | 27 | function obj = HuberLoss(varargin) 28 | obj.load(varargin) ; 29 | obj.sigma = obj.sigma ; 30 | end 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/Interp.m: -------------------------------------------------------------------------------- 1 | classdef Interp < dagnn.Layer 2 | properties 3 | zoomFactor = 1 4 | shrinkFactor = 1 5 | padBeg = 0 6 | padEnd = 0 7 | end 8 | 9 | methods 10 | function outputs = forward(obj, inputs, params) 11 | outputs{1} = vl_nninterp(inputs{1}, obj.shrinkFactor, ... 12 | obj.zoomFactor, 'padBeg', obj.padBeg, 'padEnd', obj.padEnd) ; 13 | end 14 | 15 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 16 | derInputs{1} = vl_nninterp(inputs{1}, obj.shrinkFactor, ... 17 | obj.zoomFactor, derOutputs{1}, 'padBeg', obj.padBeg, ... 18 | 'padEnd', obj.padEnd) ; 19 | derParams = {} ; 20 | end 21 | 22 | function obj = Interp(varargin) 23 | obj.load(varargin{:}) ; 24 | obj.zoomFactor = obj.zoomFactor ; 25 | end 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/L2Norm.m: -------------------------------------------------------------------------------- 1 | classdef L2Norm < dagnn.ElementWise 2 | 3 | properties 4 | % keep the name "param" for compatibility with previous implementations 5 | param = 1e-10 ; 6 | end 7 | 8 | methods 9 | function outputs = forward(obj, inputs, params) 10 | outputs{1} = vl_nnl2norm(inputs{1}, 'epsilon', obj.param) ; 11 | end 12 | 13 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 14 | derInputs{1} = vl_nnl2norm(inputs{1}, derOutputs{1}, 'epsilon', obj.param) ; 15 | derParams = {} ; 16 | end 17 | 18 | function rfs = getReceptiveFields(obj) 19 | rfs.size = [1 1] ; 20 | rfs.stride = [1 1] ; 21 | rfs.offset = [1 1] ; 22 | end 23 | 24 | function obj = L2Norm(varargin) 25 | obj.load(varargin) ; 26 | end 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/Max.m: -------------------------------------------------------------------------------- 1 | classdef Max < dagnn.ElementWise 2 | %SUM DagNN max layer 3 | % The MAX layer takes the max of all its inputs and store the result 4 | % as its only output. 5 | 6 | properties (Transient) 7 | numInputs 8 | end 9 | 10 | methods 11 | function outputs = forward(obj, inputs, params) 12 | obj.numInputs = numel(inputs) ; 13 | outputs{1} = vl_nnmax(obj.numInputs, inputs{:}) ; 14 | end 15 | 16 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 17 | derInputs = vl_nnmax(obj.numInputs, inputs{:}, derOutputs{1}) ; 18 | keyboard 19 | derParams = {} ; 20 | end 21 | 22 | function outputSizes = getOutputSizes(obj, inputSizes) 23 | outputSizes{1} = inputSizes{1} ; 24 | for k = 2:numel(inputSizes) 25 | if all(~isnan(inputSizes{k})) && all(~isnan(outputSizes{1})) 26 | if ~isequal(inputSizes{k}, outputSizes{1}) 27 | warning('Max layer: the dimensions of the input variables is not the same.') ; 28 | end 29 | end 30 | end 31 | end 32 | 33 | function rfs = getReceptiveFields(obj) 34 | numInputs = numel(obj.net.layers(obj.layerIndex).inputs) ; 35 | rfs.size = [1 1] ; 36 | rfs.stride = [1 1] ; 37 | rfs.offset = [1 1] ; 38 | rfs = repmat(rfs, numInputs, 1) ; 39 | end 40 | 41 | function obj = Max(varargin) 42 | obj.load(varargin) ; 43 | end 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/Normalize.m: -------------------------------------------------------------------------------- 1 | classdef Normalize < dagnn.ElementWise 2 | 3 | properties 4 | channelShared = []; 5 | acrossSpatial = []; 6 | end 7 | 8 | methods 9 | function outputs = forward(obj, inputs, params) 10 | outputs{1} = vl_nnscalenorm(inputs{1}, params{1}) ; 11 | end 12 | 13 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 14 | ders = vl_nnscalenorm(inputs{1}, params{1}, derOutputs{1}) ; 15 | [derInputs, derParams] = deal(ders(1), ders(2)) ; 16 | end 17 | 18 | function outputSizes = getOutputSizes(obj, inputSizes) 19 | outputSizes = inputSizes ; 20 | end 21 | 22 | function rfs = getReceptiveFields(obj) 23 | end 24 | 25 | function load(obj, varargin) 26 | s = dagnn.Layer.argsToStruct(varargin{:}) ; 27 | load@dagnn.Layer(obj, s) ; 28 | end 29 | 30 | function obj = Normalize(varargin) 31 | obj.load(varargin{:}) ; 32 | end 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/Permute.m: -------------------------------------------------------------------------------- 1 | classdef Permute < dagnn.ElementWise 2 | properties 3 | order 4 | end 5 | 6 | methods 7 | function outputs = forward(obj, inputs, params) 8 | outputs{1} = permute(inputs{1}, obj.order); 9 | end 10 | 11 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 12 | derInputs{1} = ipermute(derOutputs{1}, obj.order) ; 13 | derParams = {} ; 14 | end 15 | 16 | function outputSizes = getOutputSizes(obj, inputSizes) 17 | outputSizes{1} = inputSizes{1}(obj.order) ; 18 | end 19 | 20 | function rfs = getReceptiveFields(obj) 21 | rfs = {} ; 22 | end 23 | 24 | function load(obj, varargin) 25 | s = dagnn.Layer.argsToStruct(varargin{:}) ; 26 | load@dagnn.Layer(obj, s) ; 27 | end 28 | 29 | function obj = Permute(varargin) 30 | obj.load(varargin{:}) ; 31 | obj.order = obj.order ; 32 | end 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/Reshape.m: -------------------------------------------------------------------------------- 1 | classdef Reshape < dagnn.ElementWise 2 | properties 3 | shape = {} ; 4 | end 5 | 6 | properties (Transient) 7 | inputSizes = {} 8 | end 9 | 10 | methods 11 | function outputs = forward(obj, inputs, params) 12 | outputs{1} = vl_nnreshape(inputs{1}, obj.shape) ; 13 | obj.inputSizes = cellfun(@size, inputs, 'UniformOutput', false) ; 14 | end 15 | 16 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 17 | derInputs{1} = vl_nnreshape(inputs{1}, obj.shape, derOutputs{1}) ; 18 | derParams = {} ; 19 | end 20 | 21 | function outputSizes = getOutputSizes(obj, inputSizes) 22 | tmp = zeros(inputSizes{1}) ; 23 | reshaped = vl_nnreshape(tmp, obj.shape) ; 24 | outSz = ones(1,4) ; 25 | outSz(1:numel(size(reshaped))) = size(reshaped) ; 26 | outputSizes{1} = outSz ; 27 | end 28 | 29 | function rfs = getReceptiveFields(obj) 30 | end 31 | 32 | function load(obj, varargin) 33 | s = dagnn.Layer.argsToStruct(varargin{:}) ; 34 | load@dagnn.Layer(obj, s) ; 35 | end 36 | 37 | function obj = Reshape(varargin) 38 | obj.load(varargin{:}) ; 39 | end 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/Slice.m: -------------------------------------------------------------------------------- 1 | classdef Slice < dagnn.ElementWise 2 | properties 3 | dim = 3 4 | slicePoint = 3 5 | end 6 | 7 | properties (Transient) 8 | inputSizes = {} 9 | end 10 | 11 | methods 12 | function outputs = forward(obj, inputs, params) 13 | outputs = vl_nnslice(inputs{1}, obj.dim, obj.slicePoint, []) ; 14 | obj.inputSizes = cellfun(@size, inputs, 'UniformOutput', false) ; 15 | end 16 | 17 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 18 | derInputs = vl_nnslice(inputs, obj.dim, obj.slicePoint, ... 19 | derOutputs, 'inputSizes', obj.inputSizes) ; 20 | derParams = {} ; 21 | end 22 | 23 | function reset(obj) 24 | obj.inputSizes = {} ; 25 | end 26 | 27 | function outputSizes = getOutputSizes(obj, inputSizes) 28 | sz = inputSizes{1} ; 29 | for k = 2:numel(inputSizes) 30 | sz(obj.dim) = sz(obj.dim) + inputSizes{k}(obj.dim) ; 31 | end 32 | outputSizes{1} = sz ; 33 | end 34 | 35 | function rfs = getReceptiveFields(obj) 36 | numInputs = numel(obj.net.layers(obj.layerIndex).inputs) ; 37 | if obj.dim == 3 || obj.dim == 4 38 | rfs = getReceptiveFields@dagnn.ElementWise(obj) ; 39 | rfs = repmat(rfs, numInputs, 1) ; 40 | else 41 | for i = 1:numInputs 42 | rfs(i,1).size = [NaN NaN] ; 43 | rfs(i,1).stride = [NaN NaN] ; 44 | rfs(i,1).offset = [NaN NaN] ; 45 | end 46 | end 47 | end 48 | 49 | function load(obj, varargin) 50 | s = dagnn.Layer.argsToStruct(varargin{:}) ; 51 | % backward file compatibility 52 | if isfield(s, 'numInputs'), s = rmfield(s, 'numInputs') ; end 53 | load@dagnn.Layer(obj, s) ; 54 | end 55 | 56 | function obj = Slice(varargin) 57 | obj.load(varargin{:}) ; 58 | end 59 | end 60 | end 61 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/SoftMaxTranspose.m: -------------------------------------------------------------------------------- 1 | classdef SoftMaxTranspose < dagnn.ElementWise 2 | 3 | properties 4 | dim = 1 5 | end 6 | 7 | methods 8 | function outputs = forward(obj, inputs, params) 9 | outputs{1} = vl_nnsoftmaxt(inputs{1}, 'dim', obj.dim) ; 10 | end 11 | 12 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 13 | derInputs{1} = vl_nnsoftmaxt(inputs{1}, derOutputs{1}, 'dim', obj.dim) ; 14 | derParams = {} ; 15 | end 16 | 17 | function obj = SoftMax(varargin) 18 | obj.load(varargin) ; 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/SoftmaxCELoss.m: -------------------------------------------------------------------------------- 1 | classdef SoftmaxCELoss < dagnn.Loss 2 | 3 | properties 4 | temperature = 1 5 | logitTargets = false 6 | end 7 | 8 | methods 9 | function outputs = forward(obj, inputs, params) 10 | outputs{1} = vl_nnsoftmaxceloss(inputs{1}, inputs{2}, ... 11 | 'temperature', obj.temperature, ... 12 | 'logitTargets', obj.logitTargets) ; 13 | n = obj.numAveraged ; 14 | m = n + size(inputs{1}, 4) ; 15 | obj.average = (n * obj.average + gather(outputs{1})) / m ; 16 | obj.numAveraged = m ; 17 | end 18 | 19 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 20 | derInputs{1} = vl_nnsoftmaxceloss(inputs{1}, inputs{2}, derOutputs{1}, ... 21 | 'temperature', obj.temperature, ... 22 | 'logitTargets', obj.logitTargets) ; 23 | derInputs{2} = [] ; 24 | derParams = {} ; 25 | end 26 | 27 | function obj = SoftmaxCELoss(varargin) 28 | obj.load(varargin) ; 29 | obj.temperature = obj.temperature ; 30 | obj.logitTargets = obj.logitTargets ; 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/TukeyLoss.m: -------------------------------------------------------------------------------- 1 | classdef TukeyLoss < dagnn.Loss 2 | 3 | properties 4 | sigma = 1. 5 | end 6 | 7 | methods 8 | function outputs = forward(obj, inputs, params) 9 | outputs{1} = vl_nntukeyloss(inputs{1}, inputs{2}, ... 10 | 'instanceWeights', inputs{3}, ... 11 | obj.opts{:}) ; 12 | n = obj.numAveraged ; 13 | m = n + size(inputs{1}, 4) ; 14 | obj.average = (n * obj.average + gather(outputs{1})) / m ; 15 | obj.numAveraged = m ; 16 | end 17 | 18 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 19 | derInputs{1} = vl_nntukeyloss(inputs{1}, inputs{2}, derOutputs{1}, ... 20 | 'instanceWeights', inputs{3}, ... 21 | obj.opts{:}) ; 22 | derInputs{2} = [] ; 23 | derInputs{3} = [] ; 24 | derParams = {} ; 25 | end 26 | 27 | function obj = TukeyLoss(varargin) 28 | obj.load(varargin) ; 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/+dagnn/VerboseLoss.m: -------------------------------------------------------------------------------- 1 | classdef VerboseLoss < dagnn.Loss 2 | 3 | methods 4 | function outputs = forward(obj, inputs, params) 5 | outputs{1} = vl_nnloss(inputs{1}, inputs{2}, [], 'loss', obj.loss, obj.opts{:}) ; 6 | %preds = squeeze(gather(inputs{1})) ; 7 | %labels = reshape(gather(inputs{2}), 1, []) ; 8 | obj.accumulateAverage(inputs, outputs); 9 | end 10 | 11 | function [derInputs, derParams] = backward(obj, inputs, params, derOutputs) 12 | derInputs{1} = vl_nnloss(inputs{1}, inputs{2}, derOutputs{1}, 'loss', obj.loss, obj.opts{:}) ; 13 | derInputs{2} = [] ; 14 | derParams = {} ; 15 | end 16 | 17 | function outputSizes = getOutputSizes(obj, inputSizes, paramSizes) 18 | outputSizes{1} = [1 1 1 inputSizes{1}(4)] ; 19 | end 20 | 21 | function rfs = getReceptiveFields(obj) 22 | % the receptive field depends on the dimension of the variables 23 | % which is not known until the network is run 24 | rfs(1,1).size = [NaN NaN] ; 25 | rfs(1,1).stride = [NaN NaN] ; 26 | rfs(1,1).offset = [NaN NaN] ; 27 | rfs(2,1) = rfs(1,1) ; 28 | end 29 | 30 | function obj = VerboseLoss(varargin) 31 | obj.load(varargin) ; 32 | end 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnaxpy.m: -------------------------------------------------------------------------------- 1 | function [y, dzdx1, dzdx2] = vl_nnaxpy(a, x1, x2, varargin) 2 | % VL_NNAXPY - perform a channelwise multilpy and addition 3 | % Y = VL_NNAXPY(A, X1, X2) computes the result Y = A * X1 + X2 4 | % where X1 and X2 are HxWxCxN tensors and A is a 1x1xC array. 5 | % 6 | % Copyright (C) 2017 Samuel Albanie 7 | % Licensed under The MIT License [see LICENSE.md for details] 8 | [~, dzdy] = vl_argparsepos(struct(), varargin) ; 9 | 10 | if isempty(dzdy) 11 | y = bsxfun(@times, a, x1) + x2 ; 12 | else 13 | dzdx2 = dzdy{1} ; 14 | dzdx1 = bsxfun(@times, a, dzdy{1}) ; 15 | dzda = sum(sum(x1 .* dzdy{1}, 1), 2) ; 16 | y = dzda ; 17 | end 18 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nncaffepool.m: -------------------------------------------------------------------------------- 1 | function y = vl_nncaffepool(x, poolSize, varargin) 2 | %VL_NNCAFFEPOOL(X) - Apply Caffe-style padded pooling 3 | % Y = VL_NNCAFFEPOOL(X, POOLSIZE) This layer implements Caffe-style pooling, 4 | % which applies the pooling kernel to the padding, as well as to the input 5 | % (unlike MatConvNet which does not include the padding itself in the 6 | % kernel computation). To mimic this effect, we "pre-pad" the input using 7 | % an empty convolution, then pass to the standard MatConvNet pooling layer. 8 | % See the docs fo VL_NNPOOL to understand the full pooling operation. 9 | % 10 | % VL_NNCAFFEPOOL(..., 'option', value, ...) takes the following option: 11 | % 12 | % `Method`:: 'max' 13 | % Specify method of pooling. It can be either 'max' (retain max value 14 | % over the pooling region per channel) or 'avg' (compute the average 15 | % value over the pooling region per channel). 16 | % 17 | % `Pad`:: 0 18 | % The amount of input padding. Input images are padded with zeros 19 | % by this number of pixels on all sides before the convolution is 20 | % computed. It can also be a vector [TOP BOTTOM LEFT RIGHT] to 21 | % specify a different amount of padding in each direction. The 22 | % size of the pooling filter has to exceed the padding. Unlike standard 23 | % VL_NNPOOL, this padding is added before the pooling kernel is applied. 24 | % 25 | % Copyright (C) 2018 Samuel Albanie 26 | % Licensed under The MIT License [see LICENSE.md for details] 27 | 28 | opts.pad = 0 ; 29 | opts.stride = 1 ; 30 | opts.method = 'avg' ; 31 | opts.extraArgs = {'cuDNN'} ; 32 | [opts, dzdy] = vl_argparsepos(opts, varargin) ; 33 | 34 | padded = vl_nnconv(x, [], [], 'pad', opts.pad, opts.extraArgs{:}) ; 35 | 36 | if isempty(dzdy) 37 | y = vl_nnpool(padded, poolSize, 'pad', 0, 'stride', opts.stride, ... 38 | 'method', opts.method, opts.extraArgs{:}) ; 39 | else 40 | dzdy1 = vl_nnpool(padded, poolSize, dzdy{1}, 'pad', 0, 'stride', opts.stride, ... 41 | 'method', opts.method, opts.extraArgs{:}) ; 42 | dzdy = vl_nnconv(x, [], [], dzdy1, 'pad', opts.pad, opts.extraArgs{:}) ; 43 | y = dzdy ; 44 | end 45 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnchannelshuffle.m: -------------------------------------------------------------------------------- 1 | function y = vl_nnchannelshuffle(x, group, varargin) 2 | % VL_NNCHANNELSHUFFLE Channel shuffling 3 | % Y = VL_NNRESHAPE(X, SHAPE) reshpaes the input data X to have 4 | % the dimensions specified by SHAPE. X is a SINGLE array of 5 | % dimension H x W x D x N where (H,W) are the height and width of 6 | % the map stack, D is the image depth (number of feature channels) 7 | % and N the number of of images in the stack. SHAPE is a 1 x 3 cell 8 | % array, the contents of which are passed in order to the MATLAB 9 | % reshape function. As a consequence, `[]` an be used to specify a 10 | % dimension which should be computed from the other two. The batch size 11 | % (the fourth dimension of the input) is left unchanged by this 12 | % reshaping operation. 13 | % 14 | % Example: 15 | % Inputs: X with shape [100 100 3 5] and SHAPE = { 100 3 [] } 16 | % will produce an output Y with shape [100 3 100 5] 17 | % 18 | % DZDX = VL_NNRESHAPE(X, SHAPE, DZDY) computes the derivatives of the 19 | % block projected onto DZDY. DZDX and DZDY have the same dimensions 20 | % as X and Y respectively. 21 | % 22 | % This operation was originally described in: 23 | % 24 | % Zhang, X., Zhou, X., Lin, M., & Sun, J. (2017). 25 | % ShuffleNet: An Extremely Efficient Convolutional Neural Network for 26 | % Mobile Devices. arXiv preprint arXiv:1707.01083. 27 | % 28 | % Copyright (C) 2017 Samuel Albanie 29 | % Licensed under The MIT License [see LICENSE.md for details] 30 | 31 | [~, dzdy] = vl_argparsepos(struct(), varargin) ; 32 | keyboard 33 | 34 | batchSize = size(x, 4) ; 35 | 36 | if isempty(dzdy) 37 | y = reshape(x, shape{1}, shape{2}, shape{3}, batchSize) ; 38 | else 39 | y = reshape(dzdy{1}, size(x)) ; 40 | end 41 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nncrop_wrapper.m: -------------------------------------------------------------------------------- 1 | function y = vl_nncrop_wrapper(x1, x2, crop, dzdy) 2 | %VL_NNCROP_WRAPPER AutoNN wrapper for MatConvNet's vl_nncrop 3 | % This wrapper computes adaptive crop sizes (as used in the 4 | % FCN segmentation framework) to enable direct use of the 5 | % vl_nncrop interface by cropping X1 to match the size of X2 6 | % 7 | % Copyright (C) 2017 Samuel Albanie 8 | % Licensed under The MIT License [see LICENSE.md for details] 9 | 10 | v2 = size(x1,1) - size(x2,1) ; 11 | u2 = size(x1,2) - size(x2,2) ; 12 | v1 = max(0, v2 - crop(1)) ; 13 | u1 = max(0, u2 - crop(2)) ; 14 | adjCrop = [v2 - v1, v1, u2 - u1, u1] ; 15 | if nargin < 4 16 | y = vl_nncrop(x1, adjCrop) ; 17 | else % backward pass (returned for x1 only) 18 | y = vl_nncrop(x1, adjCrop, dzdy) ; 19 | end 20 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nneuclideanloss.m: -------------------------------------------------------------------------------- 1 | function y = vl_nneuclideanloss(x, t, varargin) 2 | % VL_NNEUCLIDEANLOSS computes the L2 Loss 3 | % Y = VL_NNEUCLIDEANLOSS(X, T) computes the Euclidean Loss 4 | % (also known as the L2 loss) between an N x 1 array of input 5 | % predictions, X and an N x 1 array of targets, T. The output 6 | % Y is a scalar value. 7 | % 8 | % Copyright (C) 2017 Samuel Albanie 9 | % All rights reserved. 10 | 11 | opts.instanceWeights = ones(size(x)) ; 12 | [opts, dzdy] = vl_argparsepos(opts, varargin, 'nonrecursive') ; 13 | 14 | % residuals 15 | res = x - t ; 16 | 17 | if isempty(dzdy) 18 | resSq = res.^2 ; 19 | weighted = (1/2) * opts.instanceWeights .* resSq ; 20 | y = sum(weighted(:)) ; 21 | else 22 | y = opts.instanceWeights .* res * dzdy{1} ; 23 | end 24 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnflatten.m: -------------------------------------------------------------------------------- 1 | function y = vl_nnflatten(x, axis, varargin) 2 | %VL_NNFLATTEN flatten features along axis 3 | % Y = VL_NNFLATTEN(X, AXIS) flattens input data X along the given 4 | % axis. X is a SINGLE array of dimension H x W x C x N where (H,W) 5 | % are the height and width of the features, C is the number of 6 | % feature channels and N the number of of images in the batch. AXIS 7 | % is an integer between 1 and 3 defining the axis along which the 8 | % H, W and C features will be flattened. 9 | % 10 | % For example, if the AXIS is 3, then the output a is a SINGLE 11 | % array of dimensions 1 x 1 x HWC x N. 12 | 13 | % DZDX = VL_NNFLATTEN(X, AXIS, DZDY) computes the derivatives of the 14 | % block projected onto DZDY. DZDX and DZDY have the same dimensions 15 | % as X and Y respectively. 16 | % 17 | % The derivative DZDY has the same dimension of the output Y and 18 | % The derivative DZDX has the same dimension as the input X. 19 | % 20 | % Copyright (C) 2017 Samuel Albanie and Andrea Vedaldi. 21 | % Licensed under The MIT License [see LICENSE.md for details] 22 | 23 | [~, dzdy] = vl_argparsepos(struct(), varargin) ; 24 | 25 | assert(ismember(axis, [1 2 3]), 'flatten axis must be 1, 2 or 3') ; 26 | 27 | sz = size(x) ; batchSize = size(x,4) ; 28 | outputSize = [1 1 1 batchSize] ; 29 | outputSize(axis) = prod(sz(1:min(length(sz),3))) ; 30 | 31 | if isempty(dzdy) 32 | y = reshape(x, outputSize) ; 33 | else 34 | y = reshape(dzdy{1}, sz) ; 35 | end 36 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnglobalpool.m: -------------------------------------------------------------------------------- 1 | function y = vl_nnglobalpool(x, varargin) 2 | %VL_NNGLOBALPOOL CNN global poolinng. 3 | % Y = VL_NNGLOBALPOOL(X) applies the pooling operator to all 4 | % spatial locations of the data X. X is a SINGLE array of dimension 5 | % H x W x C x N where (H,W) are the height and width of the map stack, 6 | % C is the number of feature channels and N the number of of images 7 | % in the batch. 8 | % 9 | % DZDX = VL_NNGLOBALPOOL(X, POOL, DZDY) computes the derivatives of the 10 | % block projected onto DZDY. DZDX and DZDY have the same dimensions 11 | % as X and Y respectively. 12 | % 13 | % VL_NNGLOBALPOOL(..., 'option', value, ...) takes the following option: 14 | % 15 | % `method`:: 'avg' 16 | % Specify method of pooling. It can be either 'max' (retain max value 17 | % over all spatial locations per channel) or 'avg' (compute the average 18 | % value over all spatial locations per channel). 19 | % 20 | % The output a is a SINGLE array of dimensions 1 x 1 x C x N. 21 | % 22 | % The derivative DZDY has the same dimension of the output Y and 23 | % The derivative DZDX has the same dimension as the input X. 24 | % 25 | % Copyright (C) 2016 Samuel Albanie and Andrea Vedaldi 26 | % Licensed under The MIT License [see LICENSE.md for details] 27 | 28 | opts.method = 'avg' ; 29 | [opts, dzdy] = vl_argparsepos(opts, varargin) ; 30 | 31 | if nargin <= 1 || isempty(dzdy) 32 | switch opts.method 33 | case 'avg', y = mean(mean(x, 1), 2) ; 34 | case 'max', y = max(max(x, [], 1), [], 2) ; 35 | otherwise, error('Pooling method %s not recognized', opts.method) ; 36 | end 37 | else 38 | base = 1 / (size(x,1) * size(x,2)) * ones(size(x), 'like', x) ; 39 | y = bsxfun(@times, base, dzdy{1}) ; 40 | end 41 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nninterp.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/mcnExtraLayers-master/matlab/vl_nninterp.m -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnl2norm.m: -------------------------------------------------------------------------------- 1 | function y = vl_nnl2norm(x, varargin) 2 | %VL_NNL2NORM - apply L2 normalisation to features 3 | % Y = VL_NNL2NORM(X) - applies L2 normalisation to each channel of the input 4 | % tensor X (which has shape H x W x C x N). 5 | % 6 | % DZDX = VL_NNL2NORM(X, DZDY) computes the derivatives of the block 7 | % projected onto DZDY. 8 | % 9 | % VL_NNL2NORM(..., 'option', value, ...) takes the following options: 10 | % 11 | % `epsilon`:: 1e-10 12 | % Adds a small value to the normalisation factor (to avoid division by 13 | % zero). 14 | % 15 | % This function is based on another funciton with the same name by 16 | % Subhransu Maji, Aruni RoyChowdhury, Tsung-Yu Lin 17 | % 18 | % Copyright (C) 2018 Samuel Albanie 19 | % Licensed under The MIT License [see LICENSE.md for details] 20 | 21 | opts.epsilon = 1e-10 ; 22 | [opts,dzdy] = vl_argparsepos(opts, varargin) ; 23 | 24 | xNorm = sqrt(sum(x.*x, 3) + opts.epsilon) ; 25 | 26 | if isempty(dzdy) 27 | y = x ./ repmat(xNorm, [1, 1, size(x, 3)]) ; 28 | else 29 | dzdy = dzdy{1} ; 30 | A = bsxfun(@times, dzdy, xNorm.^(-1)) ; 31 | B = sum(x.*dzdy,3) .* xNorm.^(-3) ; 32 | B = bsxfun(@times, x, B) ; 33 | y = A - B ; 34 | end 35 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnmasknan.m: -------------------------------------------------------------------------------- 1 | function [mx, mt] = vl_nnmasknan(x, t, varargin) 2 | %VL_NNMASKNAN masks out NaN data from targets 3 | % [MX, MT] = VL_NNMASKNAN(X,T) masks out NaN data present in targets 4 | % T and drops the corresponding entries in X. Produces masked outputs 5 | % MX and MT where MT consists of the non-NaN entries of T and MX consists 6 | % of the corresponding entries of X. The shape of both MX and MT will be 7 | % Nx1, where N is the number of non-NaN entries of T. 8 | % 9 | % NOTE: I think this function is borrowed from somewhere, since I don't 10 | % remember writing it. Unfortunately I can't remember where it might 11 | % be from, making attribution difficult. 12 | % 13 | % Copyright (C) 2017 Samuel Albanie 14 | % Licensed under The MIT License [see LICENSE.md for details] 15 | 16 | [~, dzdy] = vl_argparsepos(struct(), varargin) ; 17 | 18 | mask = isnan(t) ; 19 | mx = x ; mt = t ; 20 | 21 | if isempty(dzdy) 22 | mx(mask(:)) = [] ; 23 | mt(mask(:)) = [] ; 24 | mx = mx' ; mt = mt' ; 25 | else 26 | mx = zeros(size(x), 'like', x) ; 27 | mx(~mask) = dzdy{1} ; 28 | end 29 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnmax.m: -------------------------------------------------------------------------------- 1 | function varargout = vl_nnmax(M, varargin) 2 | % VL_NNMAX Element-wise maximum 3 | % Y = VL_NNMAX(M, X1, ..., XM) applies the elementwise max operator to 4 | % the given M input tensors, each of which should have the same input 5 | % dimension. 6 | % 7 | % [DZDX1,..,DZDXM] = VL_NNMAX(M,X1, ...,XM, DZDY) computes the 8 | % derivatives of the block projected onto DZDY. 9 | % 10 | % Copyright (C) 2017 Samuel Albanie 11 | % Licensed under The MIT License [see LICENSE.md for details] 12 | 13 | assert(M >= 2, 'at least two input tensors expected') ; 14 | ins = varargin(1:M) ; varargin(1:M) = [] ; 15 | [~, dzdy] = vl_argparsepos(struct(), varargin) ; 16 | 17 | shared = cat(5, ins{:}) ; 18 | if isempty(dzdy) 19 | varargout{1} = max(shared, [], 5) ; 20 | else 21 | % recompute forward max and insert derivatives at max locations 22 | [~,I] = max(shared, [], 5) ; 23 | dzdx = zeros(size(shared), 'like', shared) ; 24 | offsets = (I - 1) .* numel(dzdy{1}) ; 25 | idx = offsets(:) + (1:numel(dzdy{1}))' ; 26 | dzdx(idx) = dzdy{1} ; 27 | varargout = arrayfun(@(x) {dzdx(:,:,:,:,x)}, 1:M) ; 28 | end 29 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnnonorm.m: -------------------------------------------------------------------------------- 1 | function [y, dzdg, dzdb] = vl_nnnonorm(x, g, b, varargin) 2 | %VL_NNNONORM applies weights and biases, but does no normalization 3 | % Y = VL_NNNONORM(X,G,B) applies a set of gains and biases to 4 | % the input X with shape HxWxCxN. "No normalization" is defined as: 5 | % 6 | % Y(i,j,k,t) = G(k') * X(i,j,k,t) + B(k') 7 | % 8 | % where 9 | % k' = group_idx(k,C,G), where N_G is the number of groups and 10 | % group_idx(k,C,G) := floor(k / (C/N_G)). 11 | % 12 | % VL_NNGNORM(..., 'option', value, ...) takes the following option: 13 | % 14 | % This layer was largely inspired by this blog post: 15 | % http://www.offconvex.org/2018/03/02/acceleration-overparameterization/ 16 | % 17 | % Copyright (C) 2018 Samuel Albanie 18 | % All rights reserved. 19 | 20 | [~,dzdy] = vl_argparsepos(struct(), varargin) ; 21 | 22 | expectedSz = [1 1 size(x,3) 1] ; 23 | sg = size(g) ; sb = size(b) ; 24 | assert(all(expectedSz(1:numel(sg)) == sg), 'GAINS have unexpected size') ; 25 | assert(all(expectedSz(1:numel(sb)) == sb), 'BIASES have unexpected size') ; 26 | 27 | if isempty(dzdy) 28 | y = bsxfun(@times, g, x) ; % apply gain 29 | y = bsxfun(@plus, y, b) ; % add bias 30 | else 31 | dzdy = dzdy{1} ; 32 | dzdb = chanSum(dzdy) ; 33 | dzdg = chanSum(x .* dzdy) ; 34 | dzdx = bsxfun(@times, dzdy, g) ; 35 | y = dzdx ; 36 | end 37 | 38 | % ----------------------- 39 | function res = chanSum(x) 40 | % ----------------------- 41 | res = sum(sum(sum(x, 1), 2), 4) ; 42 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnreshape.m: -------------------------------------------------------------------------------- 1 | function y = vl_nnreshape(x, shape, varargin) 2 | % VL_NNRESHAPE Feature reshaping 3 | % Y = VL_NNRESHAPE(X, SHAPE) reshpaes the input data X to have 4 | % the dimensions specified by SHAPE. X is a SINGLE array of 5 | % dimension H x W x D x N where (H,W) are the height and width of 6 | % the map stack, D is the image depth (number of feature channels) 7 | % and N the number of of images in the stack. SHAPE is a 1 x 3 cell 8 | % array, the contents of which are passed in order to the MATLAB 9 | % reshape function. As a consequence, `[]` an be used to specify a 10 | % dimension which should be computed from the other two. The batch size 11 | % (the fourth dimension of the input) is left unchanged by this 12 | % reshaping operation. 13 | % 14 | % Alternatively, SHAPE can be specified in the "caffe style", as an 15 | % array, using `0` to indicate that a dimension should be preserved and 16 | % `-1` to indicate a dimension that should be computed from the others 17 | % (this serves the same role as [] in the standard MATLAB convention). 18 | % 19 | % Example: 20 | % Inputs: X with shape [100 100 3 5] and SHAPE = { 100 3 [] } 21 | % will produce an output Y with shape [100 3 100 5] 22 | % 23 | % DZDX = VL_NNRESHAPE(X, SHAPE, DZDY) computes the derivatives of the 24 | % block projected onto DZDY. DZDX and DZDY have the same dimensions 25 | % as X and Y respectively. 26 | % 27 | % Copyright (C) 2017 Samuel Albanie and Andrea Vedaldi. 28 | % Licensed under The MIT License [see LICENSE.md for details] 29 | 30 | [~, dzdy] = vl_argparsepos(struct(), varargin) ; 31 | 32 | if isnumeric(shape) % apply caffe style conventions if needed 33 | shape_ = num2cell(shape) ; 34 | if numel(shape_) == 2, shape_{3} = [] ; end 35 | k = find(shape == -1) ; if k, shape_{k} = [] ; end 36 | k = find(shape == 0) ; 37 | if k, rep = arrayfun(@(i) {size(x,i)}, k) ; shape_(k) = rep ; end 38 | shape = shape_ ; 39 | end 40 | 41 | batchSize = size(x, 4); 42 | 43 | if isempty(dzdy) 44 | y = reshape(x, shape{1}, shape{2}, shape{3}, batchSize) ; 45 | else 46 | y = reshape(dzdy{1}, size(x)) ; 47 | end 48 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnrmse.m: -------------------------------------------------------------------------------- 1 | function y = vl_nnmrse(x, t, varargin) 2 | % VL_NNRMSE computes the root mean square error 3 | % Y = VL_NNRMSE(X, T) computes the root mean square error between 4 | % predictions X and targets T, where X and T are Nx1 arrays, and 5 | % Y takes a scalar value 6 | % 7 | % Copyright (C) 2017 Samuel Albanie 8 | % All rights reserved. 9 | 10 | opts.residualScale = 1 ; 11 | [opts, dzdy] = vl_argparsepos(opts, varargin, 'nonrecursive') ; 12 | assert(isempty(dzdy), 'using rmse as a loss is surely madness?') 13 | 14 | % residuals 15 | res = x - t ; 16 | y = sqrt((1/numel(res)) * (opts.residualScale * res(:)).^2) ; 17 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnscale.m: -------------------------------------------------------------------------------- 1 | function [y,dzdx2,dzdb] = vl_nnscale(x1, x2, b, varargin) 2 | % VL_NNSCALE Apply feature scale and offset 3 | % Y = VL_NNSCALE(X1, X2, B) rescales array X1 by array X2 and adds a 4 | % a bias B where X1 has shape H1 x W1 x C1 x N, X2 has shape 5 | % H2 x W2 x C2 x N and B has shape H3 x W3 x C3. These shapes 6 | % must match along non-singleton dimensions. The bias term B may 7 | % also be an empty array, in which case no offset is applied. 8 | % 9 | % [DZDX1, DZDX2, DZDB] = VL_NNSCALE(X1, X2, B, DZDY) computes the 10 | % derivatives of the block projected onto DZDY. DZDX1, DZDX2 and 11 | % DZDB have the same dimensions as X1, X2 and B respectively. 12 | % 13 | % Copyright (C) 2017 Samuel Albanie. 14 | % Licensed under The MIT License [see LICENSE.md for details] 15 | 16 | opts.size = [0 0 0 0] ; 17 | [~, dzdy] = vl_argparsepos(opts, varargin) ; 18 | 19 | if isempty(dzdy) 20 | y = bsxfun(@times, x1, x2) ; 21 | if ~isempty(b), y = bsxfun(@plus, y, b) ; end 22 | else 23 | dzdx1 = bsxfun(@times, dzdy{1}, x2) ; 24 | dzdx2 = bsxfun(@times, dzdy{1}, x1) ; 25 | % perform some magic to "undo" the bsxfun effect for the derivative 26 | % (NOTE: here we are assuming that expanded singletons lie in x2, 27 | % -> this should be addressed) 28 | msg = 'this implementation expects any singletons to occur in X2, not X1' ; 29 | sz1 = size(x1) ; sz2 = size(x2) ; n = min(numel(sz1), numel(sz2)) ; 30 | assert(all(sz2(1:n) <= sz1(1:n)), msg) ; 31 | sz = [sz2 1 1 1 1] ; sz = sz(1:4) ; 32 | for k = find(sz == 1), dzdx2 = sum(dzdx2, k) ; end 33 | 34 | if ~isempty(b) 35 | dzdb = dzdy{1} ; szb = size(b) ; n = numel(szb) ; 36 | sz = [1 1 1 1] ; sz(1:n) = szb ; % handle matlab dropping of singletons 37 | for k = find(sz == 1), dzdb = sum(dzdb, k) ; end 38 | else 39 | dzdb = [] ; 40 | end 41 | y = dzdx1 ; 42 | end 43 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnscalenorm.m: -------------------------------------------------------------------------------- 1 | function [y,dzdw] = vl_nnscalenorm(x, w, varargin) 2 | %VL_NNSCALENORM Feature normalization with scaling. 3 | % Y = VL_NNSCALENORM(X, W) normalizes input features across 4 | % across channels to have an L2 norm of 1, and scales each 5 | % channel by a learnable weight according to the following 6 | % formula: 7 | % 8 | % Y(i,j,c,n) = X(i,j,c,n) * W(1,1,c) / sum_{k=1}^C (X(i,j,k,n)^2) 9 | % 10 | % where X is an H x W x C x N 4D tensor input, Y is the 11 | % H x W x C x N tensor output and W is a 1 x 1 x Q tensor of 12 | % weights whose number of channels `Q` depends on the choice of 13 | % `channelShared` option value described below. 14 | % 15 | % [DX, DW] = VL_NNSCALENORM(X, W, DY) computes the derivatives of 16 | % the operator projected onto P. DX and DW have the same 17 | % dimensions as X and W. The derivatives with respect to the weights 18 | % W are given by 19 | % 20 | % dzDW(1,1,c,1) = X(i,j,k,n) / sum_{k=1}^K (X(i,j,k,n)^2) 21 | % 22 | % NOTES: This layer was introduced in the paper: "ParseNet: Looking Wider 23 | % To See Better". It is useful when combining activations from different 24 | % layers of the network that might possess different scales. 25 | % 26 | % Copyright (C) 2017 Samuel Albanie 27 | % Licensed under The MIT License [see LICENSE.md for details] 28 | 29 | [~, dzdy] = vl_argparsepos(struct(), varargin) ; 30 | 31 | sz = [1 1 1 1] ; 32 | sz(1:numel(size(x))) = size(x) ; 33 | multipliers = repmat(w, [sz(1:2) 1 size(x,4)]) ; 34 | 35 | %Set Local Response Normalization parameters 36 | kappa = 0 ; alpha = 1 ; beta = 0.5 ; N = 2 * size(x,3) ; 37 | normParams = [N kappa alpha beta] ; 38 | normalizedFeats = vl_nnnormalize(x, normParams) ; 39 | 40 | if isempty(dzdy) 41 | y = multipliers .* vl_nnnormalize(x, [N kappa alpha beta]) ; 42 | else 43 | dzdw_ = dzdy{1} .* normalizedFeats ; 44 | dzdw = sum(sum(sum(dzdw_,1), 2), 4) ; 45 | dzdx = vl_nnnormalize(x, normParams, multipliers .* dzdy{1}) ; 46 | y = dzdx ; 47 | end 48 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnslice.m: -------------------------------------------------------------------------------- 1 | function y = vl_nnslice(X, dim, slicePoint, dzdy, varargin) 2 | %VL_NNSLICE slices a single input tensor into multiple outputs. 3 | % 4 | % Y = VL_NNSLICE(X, DIM, SLICEPOINT) slices the input X 5 | % along dimension DIM at the points specified by SLICEPOINT, to 6 | % produce a cell array of outputs Y. The number of slices is 7 | % determined by the number of values contained in SLICEPOINT. 8 | % 9 | % DZDX = VL_NNSLICE(X, DIM, SLICEPOINT, DZDY) computes the derivatives 10 | % of the block projected onto DZDY. DZDX has the same dimensions 11 | % as X, while the DZDY and Y are cell arrays with matching element 12 | % sizes. 13 | % 14 | % Copyright (C) 2017 Samuel Albanie. 15 | % Licensed under The MIT License [see LICENSE.md for details] 16 | 17 | opts.inputSizes = [] ; 18 | opts = vl_argparse(opts, varargin, 'nonrecursive') ; 19 | 20 | assert(~isempty(slicePoint), 'At least one slice point must be specified') ; 21 | assert(ismember(dim, [3 4]), ... 22 | 'Currently, only slicing along channels or batches is supported') ; 23 | 24 | if isempty(dzdy) 25 | sliceEnds = [slicePoint size(X, dim)] ; 26 | sliceStarts = [1 sliceEnds(1:end -1) + 1] ; 27 | slices = arrayfun(@(x,y) x:y, sliceStarts, sliceEnds, 'Uni', 0) ; 28 | subs = repmat({':'}, [numel(sliceStarts) 4]) ; 29 | subs(:,dim) = vertcat(slices) ; 30 | y = arrayfun(@(x) ... 31 | subsref(X, struct('type', '()', 'subs', {subs(x,:)})), ... 32 | 1:size(subs,1), 'Uni', 0) ; 33 | else 34 | y = {cat(dim, dzdy{:})} ; 35 | assert(isequal(opts.inputSizes{1}, size(y{1})), 'sizes do not match') ; 36 | end 37 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnsoftmaxceloss.m: -------------------------------------------------------------------------------- 1 | function y = vl_nnsoftmaxceloss(x, p, varargin) 2 | %VL_NNSOFTMAXCELOSS computes the cross entropy loss from logits 3 | % Y = VL_NNSOFTMAXCELOSS(X, P) computes the cross entropy loss between 4 | % and 1 x 1 x C x N array of predicted logits and an 1 x 1 x C x N array 5 | % of target probabilities. Note that the third dimension of P must form 6 | % valid probabilities (i.e. sum to 1, and 0<=p<=1). The output Y is a 7 | % SINGLE scalar. 8 | % 9 | % The Cross Entropy Loss between X and P is as: 10 | % 11 | % Loss = - sum_n sum_c p_{cn} log(softmax(x_n)_c) 12 | % 13 | % VL_NNSOFTMAXCELOSS(..., 'option', value, ...) takes the following options: 14 | % 15 | % `tol` :: 1e-5 16 | % Used as to control the tolerance of the sanity check that ensures that 17 | % the target distribution P is a valid probability distribution. 18 | % 19 | % `temperature`:: 1 20 | % The temperature of the softmax function. 21 | % 22 | % `logitTargets`:: false 23 | % Convert p into probabilities via a softmax of the given temperature. 24 | % 25 | % `instanceWeights`:: 1 26 | % Weights the loss contribution of each input. This can be an N x 1 27 | % array that weights each input individually, or a scalar (in which 28 | % case the same weight is applied to every input). 29 | % 30 | % Copyright (C) 2018 Samuel Albanie 31 | % Licensed under The MIT License [see LICENSE.md for details] 32 | 33 | opts.tol = 1e-5 ; 34 | opts.temperature = 1 ; 35 | opts.instanceWeights = ones(1, 1, 1, size(x,4)) ; 36 | opts.logitTargets = false ; 37 | [opts, dzdy] = vl_argparsepos(opts, varargin) ; 38 | 39 | if opts.logitTargets 40 | p = vl_nnsoftmaxt(p, 'temperature', opts.temperature, 'dim', 3) ; 41 | end 42 | 43 | 44 | % check valid probability targets 45 | normCond = all(abs(sum(p,3) - 1) < opts.tol) ; 46 | assert(normCond, 'values of p are not correctly normalized') ; 47 | rangeCond = all((0 <= p(:)) & (p(:) <= 1)) ; 48 | assert(rangeCond, 'values of p must lie between 0 and 1') ; 49 | 50 | x = x / opts.temperature ; 51 | Xmax = max(x,[],3) ; 52 | ex = exp(bsxfun(@minus, x, Xmax)) ; 53 | 54 | if isempty(dzdy) 55 | t = p .* (Xmax + log(sum(ex,3)) - x) ; 56 | weighted = opts.instanceWeights .* t ; 57 | y = sum(weighted(:)) ; 58 | else 59 | q = bsxfun(@rdivide, ex, sum(ex,3)) ; 60 | dydx = (1 / opts.temperature) * (q - p) ; 61 | weighted = opts.instanceWeights .* dydx ; 62 | y = bsxfun(@times, dzdy{1}, weighted) ; 63 | end 64 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnsoftmaxt.m: -------------------------------------------------------------------------------- 1 | function Y = vl_nnsoftmaxt(x, varargin) 2 | %VL_NNSOFTMAXT CNN softmax transpose. 3 | % Y = VL_NNSOFTMAXT(X) applies the softmax operator the data X. X 4 | % has dimension H x W x D x N, packing N arrays of W x H 5 | % D-dimensional vectors. 6 | % 7 | % D can be thought of as the number of possible classes. The function 8 | % and the function computes the softmax along the dimension specified 9 | % as an option. 10 | % 11 | % DZDX = VL_NNSOFTMAXT(X, DZDY) computes the derivative of the block 12 | % projected onto DZDY. DZDX and DZDY have the same dimensions as 13 | % X and Y respectively. 14 | % 15 | % VL_NNSOFTMAXT(.., 'option', value, ...) accepts the following options: 16 | % 17 | % `dim`:: 1 18 | % The dimension of X along which to compute the softmax. 19 | % 20 | % `temperature` :: 1 21 | % The temperature of the softmax 22 | % 23 | % This function is based on Andrea Vedaldi's vl_nnsoftmax function. 24 | % 25 | % Copyright (C) 2017 Samuel Albanie 26 | % Licensed under The MIT License [see LICENSE.md for details] 27 | 28 | opts.dim = 1 ; 29 | opts.temperature = 1 ; 30 | [opts, dzdy] = vl_argparsepos(opts, varargin) ; 31 | 32 | x = x / opts.temperature ; 33 | 34 | E = exp(bsxfun(@minus, x, max(x, [], opts.dim))) ; 35 | L = sum(E, opts.dim) ; 36 | Y = bsxfun(@rdivide, E, L) ; 37 | if isempty(dzdy) 38 | return 39 | else 40 | Y = (1 / opts.temperature) * Y ... 41 | .* bsxfun(@minus, dzdy{1}, sum(dzdy{1} .* Y, opts.dim)) ; 42 | end 43 | 44 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnspatialsoftmax.m: -------------------------------------------------------------------------------- 1 | function y = vl_nnspatialsoftmax(x, varargin) 2 | % NOTE: untested 3 | 4 | [~, dzdy] = vl_argparsepos(struct(), varargin) ; 5 | 6 | if isempty(dzdy) 7 | reshapein = reshape(x, 1,1,[],size(x,3)*size(x,4)) ; 8 | y = vl_nnsoftmax(reshapein) ; 9 | y = reshape(y, size(x)) ; 10 | else 11 | reshapein = reshape(x, 1,1,[],size(x,3)*size(x,4)) ; 12 | reshapedout = reshape(dzdy{1}, 1,1,[],size(x,3)*size(x,4)) ; 13 | y = vl_nnsoftmax(reshapein, reshapedout) ; 14 | y = reshape(y, size(x)) ; 15 | end 16 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nnsum.m: -------------------------------------------------------------------------------- 1 | function y = vl_nnsum(x1, x2, varargin) 2 | % VL_NNSUM - element-wise sum of tensors X1 and X2 3 | % Y = VL_NNSUM(X1, X2) computes the result Y = X1 + X2 4 | % where X1 and X2 are HxWxCxN tensors. 5 | % 6 | % Copyright (C) 2017 Samuel Albanie 7 | % Licensed under The MIT License [see LICENSE.md for details] 8 | [~, dzdy] = vl_argparsepos(struct(), varargin) ; 9 | 10 | if isempty(dzdy) 11 | y = x1 + x2 ; 12 | else 13 | dzdx2 = dzdy{1} ; dzdx1 = dzdy{1} ; 14 | y = {dzdx1, dzdx2} ; 15 | end 16 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/vl_nntukeyloss.m: -------------------------------------------------------------------------------- 1 | function y = vl_nntukeyloss(x, t, varargin) 2 | % VL_NNTUKEYLOSS computes the Tukey Loss 3 | % This is a slight modification of the robust loss function 4 | % contained in the deep regression codebase 5 | % https://github.com/bazilas/matconvnet-deepReg 6 | % and described in the paper: 7 | % 8 | % Robust Optimization for Deep Regression 9 | % V. Belagiannis, C. Rupprecht, G. Carneiro, and N. Navab, 10 | % ICCV 2015, Santiago de Chile. 11 | % Copyright (C) 2016 Visual Geometry Group, University of Oxford. 12 | % 13 | % (modified by Samuel Albanie, 2017) 14 | 15 | opts.scaleRes = 1 ; 16 | opts.adaptInliers = 0 ; 17 | opts.instanceWeights = ones(size(x)) ; 18 | [opts, dzdy] = vl_argparsepos(opts, varargin, 'nonrecursive') ; 19 | 20 | % residuals 21 | res = x - t ; 22 | 23 | % Median absolute deviation (MAD) 24 | MAD = 1.4826 * mad(res, 1) ; 25 | C = 4.685 ; 26 | 27 | % inliers (percentage of inliers) 28 | nonZer = round(100 * sum(abs(res(:)) < C) / numel(res)) ; 29 | 30 | % Big V says that this sometimes helps the convergence 31 | if opts.adaptInliers % as in the paper 32 | if nonZer < 70, MAD = MAD * opts.scaleRes ; end 33 | end 34 | 35 | res = bsxfun(@rdivide, res, MAD) ; 36 | 37 | if isempty(dzdy) 38 | scale = (C^2) / 6 ; 39 | yt = scale * (1 - (1 - (res ./ C).^2).^3) ; 40 | yt(abs(res) > C) = scale ; 41 | y = opts.instanceWeights(:)' * yt(:) ; 42 | else 43 | keep = boolean(abs(res) < C) ; 44 | tukDer = res .* ((1 - (res ./ C).^2).^2) ; 45 | res = tukDer * dzdy{1} .* keep .* opts.instanceWeights ; 46 | y = bsxfun(@rdivide, res, MAD) ; 47 | end 48 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/wrappers/vl_nnbrenorm_wrapper.m: -------------------------------------------------------------------------------- 1 | function [y, dzdg, dzdb, moments] = vl_nnbrenorm_wrapper(x, g, b, ... 2 | moments, clips, test, varargin) 3 | %VL_NNBRENORM_WRAPPER AutoNN wrapper for MatConvNet's vl_nnbrenorm 4 | % VL_NNBRENORM has a non-standard interface (returns a derivative for the 5 | % moments, even though they are not an input), so we must wrap it. 6 | % Layer.vl_nnbrenorm replaces a standard VL_NNBRENORM call with this one. 7 | % 8 | % Copyright (C) 2017 Samuel Albanie 9 | % (based on the autonn batchnorm wrapper by Joao F. Henriques) 10 | % All rights reserved. 11 | 12 | [opts, dzdy] = vl_argparsepos(struct(), varargin) ; 13 | 14 | if isscalar(g) 15 | g(1,1,1:size(x,3)) = g ; 16 | end 17 | if isscalar(b) 18 | b(1,1,1:size(x,3)) = b ; 19 | end 20 | if isscalar(moments) 21 | moments(1:size(x,3),1:2) = moments ; 22 | end 23 | 24 | if isempty(dzdy) 25 | y = vl_nnbrenorm(x, g, b, moments, clips, test, varargin{:}) ; 26 | else 27 | [y, dzdg, dzdb, moments] = vl_nnbrenorm(x, g, b, moments, clips, ... 28 | test, dzdy{1}, varargin{2:end}) ; 29 | 30 | if usingDeprecatedLossFn 31 | moments = moments * size(x, 4) ; 32 | end 33 | end 34 | 35 | % --------------------------------------------------------------------- 36 | function old = usingDeprecatedLossFn() 37 | % --------------------------------------------------------------------- 38 | % stolen from Joao Henriques (autonn compatibility code) 39 | 40 | % this is needed to harmonize the behavior of two versions of vl_nnloss: 41 | % the legacy behavior which *sums* the loss over the batch, and the new 42 | % behavior that takes the *average* over the batch. 43 | % first, detect if the new behavior ('normalise' option) is present. 44 | old = false ; 45 | try 46 | vl_nnloss([], [], 'normalise', true) ; 47 | catch % unrecognized option, must be the old vl_nnloss 48 | old = true ; 49 | end 50 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/compare.m: -------------------------------------------------------------------------------- 1 | % init 2 | 3 | rng(0) ; 4 | C = 3 ; 5 | x = randn(5,5,C,2) ; 6 | g = rand(1,1,C) ; 7 | b = rand(1,1,C) ; 8 | clip = [1 0] ; 9 | 10 | moments = rand(C, 2) ; 11 | 12 | %ym1 = vl_nnbnorm(x, g, b, 'moments', moments) ; 13 | test = false ; 14 | ym1 = vl_nnbnorm(x, g, b) ; 15 | ym2 = vl_nnbrenorm(x, g, b, moments, clip, test) ; 16 | 17 | r1 = norm(ym1(:)) ; 18 | r2 = norm(ym2(:)) ; 19 | 20 | mdiff = ym2 - ym1 ; 21 | 22 | fprintf('moments diff norm: %f\n', norm(mdiff(:))) ; 23 | 24 | % in test mode, moments are used 25 | moments = rand(C, 2) ; 26 | 27 | %ym1 = vl_nnbnorm(x, g, b, 'moments', moments) ; 28 | test = true ; 29 | ym1 = vl_nnbnorm(x, g, b, 'moments', moments) ; 30 | ym2 = vl_nnbrenorm(x, g, b, moments, clip, test) ; 31 | 32 | r1 = norm(ym1(:)) ; 33 | r2 = norm(ym2(:)) ; 34 | 35 | mdiff = ym2 - ym1 ; 36 | 37 | fprintf('moments test mode diff norm: %f\n', norm(mdiff(:))) ; 38 | 39 | % ------------------------------------------------------------------- 40 | % Backwards mode with moments 41 | % ------------------------------------------------------------------- 42 | 43 | % check ders 44 | dzdy = rand(size(x)) ; 45 | 46 | test = false ; 47 | [dzdx1, dzdg1, dzdb1] = vl_nnbnorm(x, g, b, dzdy) ; 48 | %[dzdx1, dzdg1, dzdb1] = vl_nnbnorm(x, g, b, dzdy, 'moments', moments) ; 49 | [dzdx2, dzdg2, dzdb2] = vl_nnbrenorm(x, g, b, moments, clip, test, dzdy) ; 50 | 51 | ddiff = dzdx2 - dzdx1 ; 52 | fprintf('diff der x: %f\n', norm(ddiff(:))) ; 53 | 54 | ddiffg = squeeze(dzdg2) - dzdg1 ; 55 | fprintf('diff der g: %f\n', norm(ddiffg(:))) ; 56 | 57 | ddiffb = squeeze(dzdb2) - dzdb1 ; 58 | fprintf('diff der b: %f\n', norm(ddiffb(:))) ; 59 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/run_brenorm_tests.m: -------------------------------------------------------------------------------- 1 | function run_brenorm_tests(varargin) 2 | % --------------------------- 3 | % run tests for BReNorm module 4 | % (based on vl_testnn) 5 | % --------------------------- 6 | 7 | opts.cpu = true ; 8 | opts.gpu = false ; 9 | opts.single = true ; 10 | opts.double = false ; 11 | opts.command = 'nn' ; 12 | opts = vl_argparse(opts, varargin) ; 13 | 14 | import matlab.unittest.constraints.* ; 15 | import matlab.unittest.selectors.* ; 16 | import matlab.unittest.plugins.TAPPlugin; 17 | import matlab.unittest.plugins.ToFile; 18 | 19 | % pick tests 20 | sel = HasName(StartsWithSubstring(opts.command)) ; 21 | if ~opts.gpu 22 | sel = sel & ~HasName(ContainsSubstring('device=gpu')) ; 23 | end 24 | if ~opts.cpu 25 | sel = sel & ~HasName(ContainsSubstring('device=cpu')) ; 26 | end 27 | if ~opts.double 28 | sel = sel & ~HasName(ContainsSubstring('dataType=double')) ; 29 | end 30 | if ~opts.single 31 | sel = sel & ~HasName(ContainsSubstring('dataType=single')) ; 32 | end 33 | 34 | % add test class to path 35 | suiteDir = fullfile(vl_rootnn, 'contrib', 'mcnBReNorm/matlab/xtest/suite') ; 36 | addpath(suiteDir) ; 37 | suite = matlab.unittest.TestSuite.fromFolder(suiteDir, sel) ; 38 | runner = matlab.unittest.TestRunner.withTextOutput('Verbosity',3); 39 | result = runner.run(suite); 40 | display(result) 41 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/run_extra_layers_tests.m: -------------------------------------------------------------------------------- 1 | function run_extra_layers_tests(varargin) 2 | % ------------------------ 3 | % run tests for ExtraLayers module 4 | % (based on vl_testnn) 5 | % ------------------------ 6 | 7 | opts.cpu = true ; 8 | opts.gpu = false ; 9 | opts.single = false ; 10 | opts.double = true ; 11 | opts.dev = false ; 12 | opts.command = 'nn' ; 13 | opts = vl_argparse(opts, varargin) ; 14 | 15 | import matlab.unittest.constraints.* ; 16 | import matlab.unittest.selectors.* ; 17 | import matlab.unittest.plugins.TAPPlugin; 18 | import matlab.unittest.plugins.ToFile; 19 | 20 | % pick tests 21 | sel = HasName(StartsWithSubstring(opts.command)) ; 22 | if ~opts.gpu 23 | sel = sel & ~HasName(ContainsSubstring('device=gpu')) ; 24 | end 25 | if ~opts.cpu 26 | sel = sel & ~HasName(ContainsSubstring('device=cpu')) ; 27 | end 28 | if ~opts.double 29 | sel = sel & ~HasName(ContainsSubstring('dataType=double')) ; 30 | end 31 | if ~opts.single 32 | sel = sel & ~HasName(ContainsSubstring('dataType=single')) ; 33 | end 34 | 35 | % add test class to path 36 | suiteDir = fullfile(vl_rootnn, 'contrib', 'mcnExtraLayers/matlab/xtest/suite') ; 37 | if opts.dev 38 | suiteDir = fullfile(suiteDir, 'dev') ; 39 | end 40 | addpath(suiteDir) ; 41 | suite = matlab.unittest.TestSuite.fromFolder(suiteDir, sel) ; 42 | runner = matlab.unittest.TestRunner.withTextOutput('Verbosity',3); 43 | result = runner.run(suite); 44 | display(result) 45 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/dev/nnl2norm.m: -------------------------------------------------------------------------------- 1 | classdef nnl2norm < nntest 2 | methods (Test) 3 | 4 | function basic(test) 5 | x = test.randn([5 5 3 3]) ; 6 | y = vl_nnl2norm(x) ; 7 | 8 | % check derivatives with numerical approximation 9 | dzdy = test.randn(size(y)) ; 10 | dzdx = vl_nnl2norm(x, dzdy) ; 11 | test.der(@(x) vl_nnl2norm(x), x, dzdy, dzdx, 1e-3*test.range) ; 12 | end 13 | 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nnaxpy.m: -------------------------------------------------------------------------------- 1 | classdef nnaxpy < nntest 2 | 3 | methods (Test) 4 | 5 | function basic(test) 6 | sz = [4,5,10,3] ; 7 | x1 = test.randn(sz) ; 8 | x2 = test.randn(sz) ; 9 | a = test.randn([1 1 sz(3) sz(4)]) ; 10 | 11 | y = vl_nnaxpy(a, x1, x2) ; 12 | dzdy = test.randn(size(y)) ; 13 | dzdx = vl_nnaxpy(a, x1, x2, dzdy) ; 14 | 15 | test.der(@(a) vl_nnaxpy(a, x1, x2), a, dzdy, dzdx{1}, 1e-3*test.range) ; 16 | test.der(@(x1) vl_nnaxpy(a, x1, x2), x1, dzdy, dzdx{2}, 1e-4*test.range) ; 17 | test.der(@(x2) vl_nnaxpy(a, x1, x2), x2, dzdy, dzdx{3}, 1e-3*test.range) ; 18 | end 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nnbrenorm.m: -------------------------------------------------------------------------------- 1 | classdef nnbrenorm < nntest 2 | properties (TestParameter) 3 | rows = {2 8 13} 4 | cols = {2 8 17} 5 | numDims = {1 3 4} 6 | batchSize = {2 7} 7 | end 8 | methods (Test) 9 | function basic(test, rows, cols, numDims, batchSize) 10 | r = rows ; 11 | c = cols ; 12 | nd = numDims ; 13 | bs = batchSize ; 14 | x = test.randn(r, c, nd, bs) ; clips = [1 0] ; 15 | moments = test.randn(nd, 2) ; 16 | g = test.randn(1, 1, nd) / test.range ; 17 | b = test.randn(1, 1, nd) / test.range ; 18 | testMode = 0 ; % training mode 19 | 20 | y = vl_nnbrenorm(x, g, b, moments, clips, testMode) ; 21 | dzdy = test.randn(size(y)) ; 22 | [dzdx,dzdg,dzdb] = vl_nnbrenorm(x, g, b, moments, clips, testMode, dzdy) ; 23 | 24 | test.der(@(x) vl_nnbrenorm(x, g, b, moments, clips, testMode), ... 25 | x, dzdy, dzdx, test.range * 1e-3) ; 26 | test.der(@(g) vl_nnbrenorm(x, g, b, moments, clips, testMode), ... 27 | g, dzdy, dzdg, 1e-2) ; 28 | test.der(@(b) vl_nnbrenorm(x, g, b, moments, clips, testMode), ... 29 | b, dzdy, dzdb, 1e-3) ; 30 | end 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nncosinesim.m: -------------------------------------------------------------------------------- 1 | classdef nncosinesim < nntest 2 | 3 | methods (Test) 4 | 5 | function basic(test) 6 | sz = [4,5,10,6] ; 7 | x1 = test.randn(sz) ; 8 | x2 = test.randn(sz) ; 9 | 10 | y = vl_nncosinesim(x1, x2) ; 11 | dzdy = test.randn(size(y)) ; 12 | [dzdx1, dzdx2] = vl_nncosinesim(x1, x2, dzdy) ; 13 | 14 | test.der(@(x1) vl_nncosinesim(x1, x2), x1, dzdy, dzdx1, 1e-4*test.range) ; 15 | test.der(@(x2) vl_nncosinesim(x1, x2), x2, dzdy, dzdx2, 1e-4*test.range) ; 16 | end 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nncrop_wrapper.m: -------------------------------------------------------------------------------- 1 | classdef nncrop_wrapper < nntest 2 | methods (Test) 3 | 4 | function basicShrink(test) 5 | batchSize = 10 ; 6 | x1 = test.randn([10 10 3 batchSize]) ; 7 | x2 = test.randn([5 5 3 batchSize]) ; 8 | crop = [1 1] ; 9 | y = vl_nncrop_wrapper(x1, x2, crop) ; 10 | 11 | % check derivatives with numerical approximation 12 | dzdy = test.randn(size(y)) ; 13 | dzdx1 = vl_nncrop_wrapper(x1, x2, crop, dzdy) ; 14 | test.der(@(x1) vl_nncrop_wrapper(x1, x2, crop), ... 15 | x1, dzdy, dzdx1, 1e-3*test.range) ; 16 | end 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nneuclideanloss.m: -------------------------------------------------------------------------------- 1 | classdef nneuclideanloss < nntest 2 | methods (Test) 3 | 4 | function basic(test) 5 | x = test.randn([100 1]) ; 6 | t = test.randn([100 1]) ; 7 | y = vl_nneuclideanloss(x, t) ; 8 | 9 | % check derivatives with numerical approximation 10 | dzdy = test.randn(size(y)) ; 11 | dzdx = vl_nneuclideanloss(x, t, dzdy) ; 12 | test.der(@(x) vl_nneuclideanloss(x, t), x, dzdy, dzdx, 1e-3*test.range) ; 13 | end 14 | 15 | function basicWithInstanceWeights(test) 16 | x = test.randn([100 1]) ; 17 | t = test.randn([100 1]) ; 18 | w = test.randn([100 1]) ; 19 | y = vl_nneuclideanloss(x, t, 'instanceWeights', w) ; 20 | 21 | % check derivatives with numerical approximation 22 | dzdy = test.randn(size(y)) ; 23 | dzdx = vl_nneuclideanloss(x, t, dzdy, 'instanceWeights', w) ; 24 | test.der(@(x) vl_nneuclideanloss(x, t, 'instanceWeights', w), x, ... 25 | dzdy, dzdx, 1e-3*test.range) ; 26 | end 27 | 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nnflatten.m: -------------------------------------------------------------------------------- 1 | classdef nnflatten < nntest 2 | methods (Test) 3 | 4 | function basic(test) 5 | sampleSize = [3,3,5,10] ; 6 | for dim = 1:3 7 | sz = sampleSize ; sz(dim) = 3 ; 8 | x = test.randn(sz) ; 9 | y1 = vl_nnflatten(x, dim) ; 10 | test.verifyEqual(size(y1,dim), prod(sz(1:3))) ; 11 | 12 | % check derivatives with numerical approximation 13 | dzdy = test.randn(size(y1)) ; 14 | dzdx = vl_nnflatten(x, dim, dzdy) ; 15 | test.der(@(x) vl_nnflatten(x, dim), x, dzdy, dzdx, 1e-3*test.range) ; 16 | end 17 | end 18 | 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nnglobalpool.m: -------------------------------------------------------------------------------- 1 | classdef nnglobalpool < nntest 2 | methods (Test) 3 | 4 | function basic(test) 5 | x = test.randn([5 5 3 3]) ; 6 | y = vl_nnglobalpool(x, 'method', 'avg') ; 7 | 8 | % check derivatives with numerical approximation 9 | dzdy = test.randn(size(y)) ; 10 | dzdx = vl_nnglobalpool(x, dzdy, 'method', 'avg') ; 11 | test.der(@(x) vl_nnglobalpool(x, 'method', 'avg'), ... 12 | x, dzdy, dzdx, 1e-3*test.range) ; 13 | end 14 | 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nngnorm.m: -------------------------------------------------------------------------------- 1 | classdef nngnorm < nntest 2 | 3 | properties (TestParameter) 4 | rows = {2 4} 5 | cols = {2 5} 6 | numDims = {4 8} 7 | batchSize = {1 2 3} 8 | groups = {4} ; 9 | end 10 | 11 | methods (Test) 12 | function basic(test, rows, cols, numDims, batchSize, groups) 13 | H = rows ; 14 | W = cols ; 15 | C = numDims ; 16 | bs = batchSize ; 17 | numGroups = groups ; 18 | x = test.randn(H, W, C, bs) ; 19 | g = test.randn(1, 1, C, 1) / test.range ; 20 | b = test.randn(1, 1, C, 1) / test.range ; 21 | 22 | args = {'numGroups', numGroups} ; 23 | y = vl_nngnorm(x, g, b, args{:}) ; 24 | dzdy = test.randn(size(y)) ; 25 | [dzdx,dzdg,dzdb] = vl_nngnorm(x, g, b, dzdy, args{:}) ; 26 | test.der(@(x) vl_nngnorm(x, g, b, args{:}), x, dzdy, dzdx, test.range * 1e-3) ; 27 | test.der(@(g) vl_nngnorm(x, g, b, args{:}), g, dzdy, dzdg, test.range * 1e-3) ; 28 | test.der(@(b) vl_nngnorm(x, g, b, args{:}), b, dzdy, dzdb, test.range * 1e-3) ; 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nnhuberloss.m: -------------------------------------------------------------------------------- 1 | classdef nnhuberloss < nntest 2 | methods (Test) 3 | 4 | function basic(test) 5 | x = test.randn([100 1]) ; 6 | t = test.randn([100 1]) ; 7 | y = vl_nnhuberloss(x, t) ; 8 | 9 | % check derivatives with numerical approximation 10 | dzdy = test.randn(size(y)) ; 11 | dzdx = vl_nnhuberloss(x, t, dzdy) ; 12 | test.der(@(x) vl_nnhuberloss(x, t), x, dzdy, dzdx, 1e-3*test.range) ; 13 | end 14 | 15 | function basicWithInstanceWeights(test) 16 | x = test.randn([100 1]) ; 17 | t = test.randn([100 1]) ; 18 | w = test.randn([100 1]) ; 19 | y = vl_nnhuberloss(x, t, 'instanceWeights', w) ; 20 | 21 | % check derivatives with numerical approximation 22 | dzdy = test.randn(size(y)) ; 23 | dzdx = vl_nnhuberloss(x, t, dzdy, 'instanceWeights', w) ; 24 | test.der(@(x) vl_nnhuberloss(x, t, 'instanceWeights', w), x, ... 25 | dzdy, dzdx, 1e-3*test.range) ; 26 | end 27 | 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nninterp.m: -------------------------------------------------------------------------------- 1 | classdef nninterp < nntest 2 | methods (Test) 3 | 4 | function basicShrink(test) 5 | zoom = 1 ; 6 | shrink = 3 ; 7 | batchSize = 10 ; 8 | x = test.randn([5 5 3 batchSize]) ; 9 | y = vl_nninterp(x, shrink, zoom) ; 10 | 11 | % check derivatives with numerical approximation 12 | dzdy = test.randn(size(y)) ; 13 | dzdx = vl_nninterp(x, shrink, zoom, dzdy) ; 14 | test.der(@(x) vl_nninterp(x, shrink, zoom), x, dzdy, dzdx, 1e-3*test.range) ; 15 | end 16 | 17 | function basicShrinkZoom(test) 18 | zoom = 4 ; 19 | shrink = 3 ; 20 | batchSize = 10 ; 21 | padBeg = 2 ; 22 | padEnd = 1 ; 23 | pad = {'padBeg', padBeg, 'padEnd', padEnd} ; 24 | x = test.randn([5 5 3 batchSize]) ; 25 | y = vl_nninterp(x, shrink, zoom, pad{:}) ; 26 | 27 | % check derivatives with numerical approximation 28 | dzdy = test.randn(size(y)) ; 29 | dzdx = vl_nninterp(x, shrink, zoom, dzdy, pad{:}) ; 30 | test.der(@(x) vl_nninterp(x, shrink, zoom, pad{:}), ... 31 | x, dzdy, dzdx, 1e-3*test.range) ; 32 | end 33 | 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nnmasknan.m: -------------------------------------------------------------------------------- 1 | classdef nnmasknan < nntest 2 | methods (Test) 3 | 4 | function basic(test) 5 | rows = 30 ; 6 | cols = 10 ; 7 | numNaN = 50 ; 8 | x = test.randn([rows cols]) ; 9 | t = test.randn([rows cols]) ; 10 | 11 | p = randperm(rows*cols) ; 12 | idx = p(1:numNaN) ; 13 | t(idx) = NaN ; 14 | 15 | [mx, mt] = vl_nnmasknan(x, t) ; 16 | 17 | % check derivatives with numerical approximation 18 | dzdy = test.rand(rows*cols - numNaN, 1) ; 19 | [dzdx,~] = vl_nnmasknan(x, t, dzdy) ; 20 | test.der(@(x) vl_nnmasknan(x, t), x, dzdy, dzdx, 1e-3*test.range) ; 21 | end 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nnmax.m: -------------------------------------------------------------------------------- 1 | classdef nnmax < nntest 2 | methods (Test) 3 | 4 | function basic(test) 5 | batchSize = 3 ; numIn = 4 ; 6 | x1 = test.randn([5 5 3 batchSize]) ; 7 | x2 = test.randn([5 5 3 batchSize]) ; 8 | x3 = test.randn([5 5 3 batchSize]) ; 9 | x4 = test.randn([5 5 3 batchSize]) ; 10 | inputs = {numIn, x1, x2, x3, x4} ; 11 | y = vl_nnmax(inputs{:}) ; 12 | 13 | % check derivatives with numerical approximation 14 | dzdy = test.randn(size(y)) ; 15 | [dzdx1,dzdx2,dzdx3,dzdx4] = vl_nnmax(inputs{:}, dzdy) ; 16 | test.der(@(x1) vl_nnmax(numIn, x1, x2, x3, x4), ... 17 | x1, dzdy, dzdx1, 1e-4*test.range) ; 18 | test.der(@(x2) vl_nnmax(numIn, x1, x2, x3, x4), ... 19 | x2, dzdy, dzdx2, 1e-4*test.range) ; 20 | test.der(@(x3) vl_nnmax(numIn, x1, x2, x3, x4), ... 21 | x3, dzdy, dzdx3, 1e-4*test.range) ; 22 | test.der(@(x4) vl_nnmax(numIn, x1, x2, x3, x4), ... 23 | x4, dzdy, dzdx4, 1e-4*test.range) ; 24 | end 25 | 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nnnonorm.m: -------------------------------------------------------------------------------- 1 | classdef nnnonorm < nntest 2 | 3 | properties (TestParameter) 4 | rows = {2 4} 5 | cols = {2 5} 6 | numDims = {4 8} 7 | batchSize = {1 2 3} 8 | end 9 | 10 | methods (Test) 11 | function basic(test, rows, cols, numDims, batchSize) 12 | H = rows ; 13 | W = cols ; 14 | C = numDims ; 15 | bs = batchSize ; 16 | x = test.randn(H, W, C, bs) ; 17 | g = test.randn(1, 1, C, 1) / test.range ; 18 | b = test.randn(1, 1, C, 1) / test.range ; 19 | 20 | y = vl_nnnonorm(x, g, b) ; 21 | dzdy = test.randn(size(y)) ; 22 | [dzdx,dzdg,dzdb] = vl_nnnonorm(x, g, b, dzdy) ; 23 | test.der(@(x) vl_nnnonorm(x, g, b), x, dzdy, dzdx, test.range * 1e-3) ; 24 | test.der(@(g) vl_nnnonorm(x, g, b), g, dzdy, dzdg, test.range * 1e-3) ; 25 | test.der(@(b) vl_nnnonorm(x, g, b), b, dzdy, dzdb, test.range * 1e-3) ; 26 | end 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nnreshape.m: -------------------------------------------------------------------------------- 1 | classdef nnreshape < nntest 2 | methods (Test) 3 | 4 | function basicWithMinus(test) 5 | sz = [3,3,5,10] ; 6 | x = test.randn(sz) ; 7 | dim = {9,[],5} ; 8 | 9 | y = vl_nnreshape(x, dim) ; 10 | targets = [9,1,5,10] ; 11 | osz = size(y) ; 12 | for i = 1:numel(targets) 13 | assert(osz(i) == targets(i)) ; 14 | end 15 | 16 | % check derivatives with numerical approximation 17 | dzdy = test.randn(size(y)) ; 18 | dzdx = vl_nnreshape(x, dim, dzdy) ; 19 | test.der(@(x) vl_nnreshape(x, dim), x, dzdy, dzdx, 1e-3*test.range) ; 20 | end 21 | 22 | function basicWithZero(test) 23 | sz = [3,3,5,10] ; 24 | x = test.randn(sz) ; 25 | dim = {[],3,5} ; 26 | 27 | y = vl_nnreshape(x, dim) ; 28 | targets = [3,3,5,10] ; 29 | osz = size(y) ; 30 | for i = 1:numel(targets) 31 | assert(osz(i) == targets(i)) ; 32 | end 33 | 34 | % check derivatives with numerical approximation 35 | dzdy = test.randn(size(y)) ; 36 | dzdx = vl_nnreshape(x, dim, dzdy) ; 37 | test.der(@(x) vl_nnreshape(x, dim), x, dzdy, dzdx, 1e-3*test.range) ; 38 | end 39 | 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nnscale.m: -------------------------------------------------------------------------------- 1 | classdef nnscale < nntest 2 | methods (Test) 3 | 4 | function basic(test) 5 | batchSize = 10 ; 6 | x1 = test.randn([5 5 3 batchSize]) ; 7 | x2 = test.randn([1 1 3 1]) ; % match along non-singletons 8 | b = [] ; 9 | y = vl_nnscale(x1, x2, b) ; 10 | 11 | % check derivatives with numerical approximation 12 | dzdy = test.randn(size(y)) ; 13 | [dzdx1, dzdx2, dzdb] = vl_nnscale(x1, x2, b, dzdy) ; 14 | test.der(@(x1) vl_nnscale(x1, x2, b), x1, dzdy, dzdx1, 1e-3*test.range) ; 15 | test.der(@(x2) vl_nnscale(x1, x2, b), x2, dzdy, dzdx2, 1e-3*test.range) ; 16 | assert(isempty(dzdb), 'bias derivative should be empty') ; 17 | end 18 | 19 | function basicBias(test) 20 | batchSize = 10 ; 21 | x1 = test.randn([5 5 3 batchSize]) ; 22 | x2 = test.randn([1 1 3 1]) ; % match along non-singletons 23 | b = test.randn([1 1 3 1]) ; % match along non-singletons 24 | y = vl_nnscale(x1, x2, b) ; 25 | 26 | % check derivatives with numerical approximation 27 | dzdy = test.randn(size(y)) ; 28 | [dzdx1, dzdx2, dzdb] = vl_nnscale(x1, x2, b, dzdy) ; 29 | test.der(@(x1) vl_nnscale(x1, x2, b), x1, dzdy, dzdx1, 1e-3*test.range) ; 30 | test.der(@(x2) vl_nnscale(x1, x2, b), x2, dzdy, dzdx2, 1e-3*test.range) ; 31 | test.der(@(b) vl_nnscale(x1, x2, b), b, dzdy, dzdb, 1e-3*test.range) ; 32 | end 33 | 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nnscalenorm.m: -------------------------------------------------------------------------------- 1 | classdef nnscalenorm < nntest 2 | methods (Test) 3 | 4 | function basic(test) 5 | batchSize = 10 ; 6 | x = test.randn([5 5 3 batchSize]) ; 7 | w = test.randn([1 1 3 1]) ; 8 | y = vl_nnscalenorm(x, w) ; 9 | 10 | % check derivatives with numerical approximation 11 | dzdy = test.randn(size(y)) ; 12 | [dzdx,dzdw] = vl_nnscalenorm(x, w, dzdy) ; 13 | test.der(@(w) vl_nnscalenorm(x, w), w, dzdy, dzdw, 1e-3*test.range) ; 14 | test.der(@(x) vl_nnscalenorm(x, w), x, dzdy, dzdx, 1e-3*test.range) ; 15 | end 16 | 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nnslice.m: -------------------------------------------------------------------------------- 1 | classdef nnslice < nntest 2 | methods (Test) 3 | 4 | function basic(test) 5 | sz = [3,3,5,4] ; 6 | x = test.randn(sz) ; 7 | dim = 4 ; 8 | slicePoints = 1:dim - 1 ; % slice along fourth dim 9 | y = vl_nnslice(x, dim, slicePoints, []) ; 10 | 11 | % check derivatives with numerical approximation 12 | dzdy = cellfun(@(x) test.randn(size(x)), y, 'Uni', 0) ; 13 | dzdx = vl_nnslice(x, dim, slicePoints, dzdy, 'inputSizes', {sz}) ; 14 | dzdy_ = cat(dim, dzdy{:}) ; 15 | dzdx_ = dzdx{1} ; 16 | test.der(@(x) forward_wrapper(x, dim, slicePoints), x, dzdy_, dzdx_, 1e-3*test.range) ; 17 | end 18 | end 19 | end 20 | 21 | % ----------------------------------------------------------------- 22 | function y = forward_wrapper(x, dim, slicePoints) 23 | % ----------------------------------------------------------------- 24 | y = vl_nnslice(x, dim, slicePoints, []) ; 25 | y = cat(dim, y{:}) ; 26 | end 27 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nnsoftmaxceloss.m: -------------------------------------------------------------------------------- 1 | classdef nnsoftmaxceloss < nntest 2 | methods (Test) 3 | 4 | function basic(test) 5 | x = test.randn([1 1 8 50]) ; 6 | p = abs(test.rand([1 1 8 50])) ; 7 | p = bsxfun(@rdivide, p, sum(p, 3)) ; 8 | y = vl_nnsoftmaxceloss(x, p) ; 9 | 10 | % check derivatives with numerical approximation 11 | dzdy = test.randn(size(y)) ; 12 | dzdx = vl_nnsoftmaxceloss(x, p, dzdy) ; 13 | test.der(@(x) vl_nnsoftmaxceloss(x, p), x, dzdy, dzdx, 1e-4*test.range) ; 14 | end 15 | 16 | function basicWithTemperature(test) 17 | x = test.randn([1 1 8 50]) ; 18 | p = abs(test.rand([1 1 8 50])) ; 19 | p = bsxfun(@rdivide, p, sum(p, 3)) ; 20 | temperature = 2 ; 21 | y = vl_nnsoftmaxceloss(x, p, 'temperature', temperature) ; 22 | 23 | % check derivatives with numerical approximation 24 | dzdy = test.randn(size(y)) ; 25 | dzdx = vl_nnsoftmaxceloss(x, p, dzdy, 'temperature', temperature) ; 26 | test.der(@(x) vl_nnsoftmaxceloss(x, p, 'temperature', temperature), x, ... 27 | dzdy, dzdx, 1e-3*test.range) ; 28 | end 29 | 30 | function basicWithInstanceWeights(test) 31 | x = test.randn([1 1 8 100]) ; 32 | p = abs(test.rand([1 1 8 100])) ; 33 | p = bsxfun(@rdivide, p, sum(p, 3)) ; 34 | w = abs(test.rand([1 1 1 100])) ; 35 | %w = w / sum(w(:)) ; 36 | %keyboard 37 | y = vl_nnsoftmaxceloss(x, p, 'instanceWeights', w) ; 38 | 39 | % check derivatives with numerical approximation 40 | dzdy = test.randn(size(y)) ; 41 | dzdx = vl_nnsoftmaxceloss(x, p, dzdy, 'instanceWeights', w) ; 42 | test.der(@(x) vl_nnsoftmaxceloss(x, p, 'instanceWeights', w), x, ... 43 | dzdy, dzdx, 1e-4*test.range) ; 44 | end 45 | 46 | function basic_softmax_logit_targets(test) 47 | x = test.randn([1 1 8 50]) ; 48 | p = abs(test.rand([1 1 8 50])) ; 49 | %p = bsxfun(@rdivide, p, sum(p, 3)) ; 50 | y = vl_nnsoftmaxceloss(x, p, 'logitTargets', true) ; 51 | 52 | % check derivatives with numerical approximation 53 | dzdy = test.randn(size(y)) ; 54 | dzdx = vl_nnsoftmaxceloss(x, p, dzdy, 'logitTargets', 1) ; 55 | test.der(@(x) vl_nnsoftmaxceloss(x, p, 'logitTargets', 1), ... 56 | x, dzdy, dzdx, 1e-4*test.range) ; 57 | end 58 | 59 | end 60 | end 61 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nnsoftmaxt.m: -------------------------------------------------------------------------------- 1 | classdef nnsoftmaxt < nntest 2 | methods (Test) 3 | 4 | function basic(test) 5 | x = test.randn([5 5 3 3]) ; 6 | y = vl_nnsoftmaxt(x) ; 7 | 8 | % check derivatives with numerical approximation 9 | dzdy = test.randn(size(y)) ; 10 | dzdx = vl_nnsoftmaxt(x, dzdy) ; 11 | test.der(@(x) vl_nnsoftmaxt(x), x, dzdy, dzdx, 1e-4*test.range) ; 12 | end 13 | 14 | function basic_temp(test) 15 | x = test.randn([5 5 3 3]) ; 16 | temperature = 7 ; 17 | y = vl_nnsoftmaxt(x, 'temperature', temperature) ; 18 | 19 | % check derivatives with numerical approximation 20 | dzdy = test.randn(size(y)) ; 21 | dzdx = vl_nnsoftmaxt(x, dzdy, 'temperature', temperature) ; 22 | test.der(@(x) vl_nnsoftmaxt(x, 'temperature', temperature), ... 23 | x, dzdy, dzdx, 1e-4*test.range) ; 24 | end 25 | 26 | function basic_dim(test) 27 | x = test.randn([5 5 3 3]) ; 28 | dim = 1 ; 29 | y = vl_nnsoftmaxt(x, 'dim', dim) ; 30 | 31 | % check derivatives with numerical approximation 32 | dzdy = test.randn(size(y)) ; 33 | dzdx = vl_nnsoftmaxt(x, dzdy, 'dim', dim) ; 34 | test.der(@(x) vl_nnsoftmaxt(x, 'dim', dim), ... 35 | x, dzdy, dzdx, 1e-4*test.range) ; 36 | end 37 | 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/matlab/xtest/suite/nntukeyloss.m: -------------------------------------------------------------------------------- 1 | classdef nntukeyloss < nntest 2 | methods (Test) 3 | 4 | function basic(test) 5 | % We have to be a little bit devious when constructing the 6 | % numerical check - if computing 7 | % x(i) + delta 8 | % changes the value of the median of the residuals, the MAD value 9 | % will also change and there will appear to be a discontinuity 10 | % Therefore, we only run derivative checks on part of the input 11 | % In particular, we deliberately run checks on a portion 12 | % the inputs (which should not trigger the change in median) 13 | n = 50 ; 14 | safety = 5 ; 15 | m = n * safety ; 16 | 17 | % create extra entries to safeguard the median 18 | xSource = sort(test.randn([m 1]) / 1) ; 19 | x = xSource(1:n) ; 20 | xPad = xSource(n+1:end) ; 21 | fullX = [x ; xPad] ; 22 | 23 | t = sort(test.randn([m 1]) / 1) ; 24 | y = vl_nntukeyloss(fullX, t) ; 25 | 26 | % check derivatives with numerical approximation 27 | dzdy = test.randn(size(y)) ; 28 | dzdx = vl_nntukeyloss(fullX, t, dzdy) ; 29 | 30 | % restrict to test range 31 | dzdx = dzdx(1:numel(x)) ; 32 | test.der(@(x) splitInputsTukey(x, t, xPad), x, dzdy, dzdx, 1e-3*test.range) ; 33 | end 34 | 35 | end 36 | end 37 | 38 | % --------------------------------------- 39 | function y = splitInputsTukey(x, t, xPad) 40 | % --------------------------------------- 41 | 42 | fullX = [x ; xPad] ; 43 | y = vl_nntukeyloss(fullX, t) ; 44 | end 45 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/setup_mcnExtraLayers.m: -------------------------------------------------------------------------------- 1 | function setup_mcnExtraLayers 2 | %SETUP_MCNEXTRALAYERS Sets up mcnExtraLayers by adding its folders to the path 3 | 4 | % add dependencies 5 | check_dependency('autonn') ; 6 | 7 | root = fileparts(mfilename('fullpath')) ; 8 | addpath(root, [root '/matlab'], [root '/matlab/wrappers'], [root '/utils']) ; 9 | 10 | % ----------------------------------- 11 | function check_dependency(moduleName) 12 | % ----------------------------------- 13 | 14 | name2path = @(name) strrep(name, '-', '_') ; 15 | setupFunc = ['setup_', name2path(moduleName)] ; 16 | if exist(setupFunc, 'file') 17 | vl_contrib('setup', moduleName) ; 18 | else 19 | % try adding the module to the path 20 | addpath(fullfile(vl_rootnn, 'contrib', moduleName)) ; 21 | if exist(setupFunc, 'file') 22 | vl_contrib('setup', moduleName) ; 23 | else 24 | waiting = true ; 25 | msg = ['module %s was not found on the MATLAB path. Would you like ' ... 26 | 'to install it now? (y/n)\n'] ; 27 | prompt = sprintf(msg, moduleName) ; 28 | while waiting 29 | str = input(prompt,'s') ; 30 | switch str 31 | case 'y' 32 | vl_contrib('install', moduleName) ; 33 | vl_contrib('compile', moduleName) ; 34 | vl_contrib('setup', moduleName) ; 35 | return ; 36 | case 'n' 37 | throw(exception) ; 38 | otherwise 39 | fprintf('input %s not recognised, please use `y` or `n`\n', str) ; 40 | end 41 | end 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/test_mcnExtraLayers.m: -------------------------------------------------------------------------------- 1 | function test_mcnExtraLayers(varargin) 2 | % run tests for ExtraLayers module 3 | 4 | opts.dev = false ; 5 | opts = vl_argparse(opts, varargin) ; 6 | 7 | % add tests to path 8 | addpath(fullfile(fileparts(mfilename('fullpath')), 'matlab/xtest')) ; 9 | addpath(fullfile(vl_rootnn, 'matlab/xtest/suite')) ; 10 | 11 | % test network layers 12 | run_extra_layers_tests('command', 'nn', 'dev', opts.dev) ; 13 | end 14 | -------------------------------------------------------------------------------- /utils/mcnExtraLayers-master/utils/fetchExternalImdb.m: -------------------------------------------------------------------------------- 1 | function loadedImdb = fetchExternalImdb(imdbPath) 2 | %FETCHEXTERNALIMDB - a helper function to avoid painful load times 3 | % LOADEDIMDB = FETCHEXTERNALIMDB(IMDBPATH) loads the imdb at the 4 | % given IMDBPATH from a global memory cache if it is available. If 5 | % not, the imdb is loaded from disk. In both cases, the loaded imdb 6 | % structure is returned as LOADEDIMDB. 7 | % with external imdbs 8 | 9 | global gImdb ; % cache 10 | global gImdbPath ; % validate the the correct imdb is being loaded 11 | 12 | if strcmp(gImdbPath, imdbPath) && ~isempty(gImdb) 13 | fprintf('found imdb in cache, re-using..\n') ; 14 | else 15 | fprintf('loading imdb ...') ; tic ; 16 | gImdb = load(imdbPath) ; 17 | fprintf('done in %g s\n', toc) ; 18 | end 19 | loadedImdb = gImdb ; 20 | -------------------------------------------------------------------------------- /utils/mod_crop.m: -------------------------------------------------------------------------------- 1 | function img = mod_crop(img, scale) 2 | % ------------------------------------------------------------------------- 3 | % Description: 4 | % crop image boundary to be the multiple of 'scale' 5 | % 6 | % Input: 7 | % - img : input image 8 | % - scale : upsampling scale 9 | % 10 | % Output: 11 | % - img : output image 12 | % 13 | % Citation: 14 | % Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution 15 | % Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang 16 | % IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017 17 | % 18 | % Contact: 19 | % Wei-Sheng Lai 20 | % wlai24@ucmerced.edu 21 | % University of California, Merced 22 | % ------------------------------------------------------------------------- 23 | 24 | if size(img, 3) == 1 25 | sz = size(img); 26 | sz = sz - mod(sz, scale); 27 | img = img(1:sz(1), 1:sz(2)); 28 | else 29 | tmpsz = size(img); 30 | sz = tmpsz(1:2); 31 | sz = sz - mod(sz, scale); 32 | img = img(1:sz(1), 1:sz(2),:); 33 | end 34 | 35 | -------------------------------------------------------------------------------- /utils/modcrop.m: -------------------------------------------------------------------------------- 1 | function imgs = modcrop(imgs, modulo) 2 | if size(imgs,3)==1 3 | sz = size(imgs); 4 | sz = sz - mod(sz, modulo); 5 | imgs = imgs(1:sz(1), 1:sz(2)); 6 | else 7 | tmpsz = size(imgs); 8 | sz = tmpsz(1:2); 9 | sz = sz - mod(sz, modulo); 10 | imgs = imgs(1:sz(1), 1:sz(2),:); 11 | end 12 | 13 | -------------------------------------------------------------------------------- /utils/model2dot.m: -------------------------------------------------------------------------------- 1 | % ------------------------------------------------------------------ 2 | % This file is copied from matconvnet repository and just has 3 | % a minor modification of getting model as the input instead of 4 | % getting the model path. 5 | % (https://github.com/vlfeat/matconvnet) 6 | % ------------------------------------------------------------------ 7 | 8 | function model2dot(obj, outPath, varargin) 9 | %MODEL2DOT Convert a model to Graphviz dot 10 | % MODEL2DOT(MODEL_PATH, OUT_PATH) Generate a graphviz dot file OUT_PATH 11 | % of MatConvNet model MODEL_PATH. 12 | % 13 | % By default, the scripts attempts to guess the input sizes based on the 14 | % network normalization options and the parameter `batchSize`. However if 15 | % network has multiple inputs, the parameter `inputs` should be specified, 16 | % without that the output dot graph does not contain the variable sizes. 17 | % 18 | % MODEL2DOT(..., 'Option', value) takes the following options: 19 | % 20 | % `BatchSize`:: 256 21 | % Default batch size in case the input size guessed from net normalization. 22 | % 23 | % `inputs`:: [] 24 | % When specified, passed to `dagnn.DagNN.print` as inputs. 25 | 26 | % Copyright (C) 2015 Karel Lenc. 27 | % All rights reserved. 28 | % 29 | % This file is part of the VLFeat library and is made available under 30 | % the terms of the BSD license (see the COPYING file). 31 | 32 | opts.batchSize = 256; 33 | opts.inputs = []; 34 | opts = vl_argparse(opts, varargin); 35 | 36 | if isstruct(obj.layers) % DAGnn format 37 | net = dagnn.DagNN.loadobj(obj); 38 | elseif iscell(obj.layers) 39 | net = dagnn.DagNN.fromSimpleNN(obj); 40 | else 41 | error('Invalid model.'); 42 | end 43 | 44 | inputs = opts.inputs; 45 | inputNames = net.getInputs(); 46 | if isempty(inputs) && numel(inputNames) == 1 ... 47 | && isfield(obj, 'meta') && isfield(obj.meta, 'normalization') ... 48 | && isfield(obj.meta.normalization, 'imageSize') 49 | inputSize = [obj.meta.normalization.imageSize(1:3), opts.batchSize]; 50 | fprintf('Input %s guessed to be: %s.\n', inputNames{1}, mat2str(inputSize)); 51 | inputs = {inputNames{1}, inputSize}; 52 | end 53 | 54 | if isempty(inputs) 55 | warning('Input sizes not specified.'); 56 | dot_c = net.print('format', 'dot'); 57 | else 58 | dot_c = net.print(inputs, 'format', 'dot'); 59 | end 60 | 61 | out_f = fopen(outPath, 'w'); 62 | if out_f == -1, error('Unable to open %s.', outPath); end; 63 | fprintf(out_f, dot_c); 64 | fclose(out_f); 65 | fprintf('Model exported to %s.\n', outPath); 66 | -------------------------------------------------------------------------------- /utils/rgb2hsi.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RSrscoder/AISD/7ca4d6d7a10d04410e6840849cb25e3c1135537a/utils/rgb2hsi.m -------------------------------------------------------------------------------- /utils/save_matrix.m: -------------------------------------------------------------------------------- 1 | function save_matrix(Q, filename, precision) 2 | % ------------------------------------------------------------------------- 3 | % Description: 4 | % save a 2D array into text file 5 | % 6 | % Input: 7 | % - Q : input matrix (2D array) 8 | % - filename : output file name 9 | % - precision : float point precision [default = 7] 10 | % 11 | % Citation: 12 | % Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution 13 | % Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang 14 | % IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017 15 | % 16 | % Contact: 17 | % Wei-Sheng Lai 18 | % wlai24@ucmerced.edu 19 | % University of California, Merced 20 | % ------------------------------------------------------------------------- 21 | 22 | if( ~exist('precision', 'var') ) 23 | precision = 7; 24 | end 25 | 26 | file = fopen(filename, 'w'); 27 | 28 | if( size(Q, 2) == 1 ) 29 | dlmwrite(filename, Q, 'precision', precision, 'delimiter', '\n', 'newline', 'unix'); 30 | else 31 | for i = 1:size(Q, 1) 32 | fprintf(file, sprintf('%%.%df\t', precision), Q(i, 1:end-1)); 33 | fprintf(file, sprintf('%%.%df', precision), Q(i, end)); 34 | fprintf(file, '\n'); 35 | end 36 | end 37 | fclose(file); 38 | 39 | end -------------------------------------------------------------------------------- /utils/shave.m: -------------------------------------------------------------------------------- 1 | function I = shave(I, border) 2 | I = I(1+border(1):end-border(1), ... 3 | 1+border(2):end-border(2), :, :); 4 | -------------------------------------------------------------------------------- /utils/shave_bd.m: -------------------------------------------------------------------------------- 1 | function img = shave_bd(img, bd) 2 | % ------------------------------------------------------------------------- 3 | % Description: 4 | % crop image boundaries for 'bd' pixels 5 | % 6 | % Input: 7 | % - img : input image 8 | % - bd : pixels to be cropped 9 | % 10 | % Output: 11 | % - img : output image 12 | % 13 | % Citation: 14 | % Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution 15 | % Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang 16 | % IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017 17 | % 18 | % Contact: 19 | % Wei-Sheng Lai 20 | % wlai24@ucmerced.edu 21 | % University of California, Merced 22 | % ------------------------------------------------------------------------- 23 | 24 | img = img(1+bd:end-bd, 1+bd:end-bd, :, :); 25 | 26 | end -------------------------------------------------------------------------------- /vllab_nn_L2_loss.m: -------------------------------------------------------------------------------- 1 | function Y = vllab_nn_L2_loss(X, Z, dzdy) 2 | % ------------------------------------------------------------------------- 3 | % Description: 4 | % L2 (MSE) loss function used in MatConvNet NN 5 | % forward : Y = vllab_nn_L2_loss(X, Z) 6 | % backward: Y = vllab_nn_L2_loss(X, Z, dzdy) 7 | % 8 | % Input: 9 | % - X : predicted data 10 | % - Z : ground truth data 11 | % - dzdy : the derivative of the output 12 | % 13 | % Output: 14 | % - Y : loss when forward, derivative of loss when backward 15 | % 16 | % Citation: 17 | % Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution 18 | % Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang 19 | % IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017 20 | % 21 | % Contact: 22 | % Wei-Sheng Lai 23 | % wlai24@ucmerced.edu 24 | % University of California, Merced 25 | % ------------------------------------------------------------------------- 26 | 27 | if nargin <= 2 28 | diff = (X - Z) .^ 2; 29 | Y = 0.5 * sum(diff(:)); 30 | else 31 | Y = (X - Z) * dzdy; 32 | end 33 | end 34 | --------------------------------------------------------------------------------