图像卷积 C++的好处在于运算速度很快,我们用R的可读性编写主函数,用C++编写卷积函数,用Rcpp将两者结合起来运行。 #include <RcppArmadillo.h> // [[Rcpp::depends(RcppArmadillo)]] using namespace arma; // mirrorIndex函数用来处理卷积时的边界溢出。 int mirrorIndex(int fetchI, int length){ if(fetchI<0) fetchI = -fetchI-1; if(fetchI >= length) fetchI = 2*length-fetchI-1; return fetchI; } // [[Rcpp::export]] // imageConv是用C++写的卷积函数 mat imageConv(mat img, mat kernel){ int c,l; c = img.n_rows; l = img.n_cols; mat img_result(c,l); int i,j,h,k,imgI,imgJ; double fin; for(i=1;i<c-1;i++){ for(j=1;j<l-1;j++){ fin = 0; for(h=-1;h<2;h++){ for (k = -1;k<2;k++){ imgI = i+h; imgJ = j+k; imgI = mirrorIndex(imgI,c); imgJ = mirrorIndex(imgJ,l); fin += img(imgI,imgJ)*kernel(h+1