# MATLAB中的最近邻插值algorithm

``function output = nearest(input) [x,y]=size(input); output = repmat(uint8(0),x*2,y*2); [newwidth,newheight]=size(output); for i=1:y for j=1:x xloc = round ((j * (newwidth+1)) / (x+1)); yloc = round ((i * (newheight+1)) / (y+1)); output(xloc,yloc) = input(j,i); end end` `

### 4 Solutions collect form web for “MATLAB中的最近邻插值algorithm”

` `%# Initializations: scale = [2 2]; %# The resolution scale factors: [rows columns] oldSize = size(inputImage); %# Get the size of your image newSize = max(floor(scale.*oldSize(1:2)),1); %# Compute the new image size %# Compute an upsampled set of indices: rowIndex = min(round(((1:newSize(1))-0.5)./scale(1)+0.5),oldSize(1)); colIndex = min(round(((1:newSize(2))-0.5)./scale(2)+0.5),oldSize(2)); %# Index old image to get new image: outputImage = inputImage(rowIndex,colIndex,:);` `

` `newSize = max(floor(scale.*oldSize(1:2)),1);` `

` `rowIndex = min(round(((1:newSize(1))-0.5)./scale(1)+0.5),oldSize(1)); colIndex = min(round(((1:newSize(2))-0.5)./scale(2)+0.5),oldSize(2));` `

` `outputImage = inputImage(rowIndex,colIndex,:);` `

` `1 c 1 scaleC*c +-----------+ 1 +----------------------+ 1 | | | | | | |----o | <=== | | | | (ii,jj) | |--------o | +-----------+ r | (i,j) | inputImage | | | | +----------------------+ scaleR*r ouputImage Note: I am using matrix notation (row/col), so: i ranges on [1,scaleR*r] , and j on [1,scaleC*c] and ii on [1,r], jj on [1,c]` `

` ` x-minX y-minY --------- = --------- maxX-minX maxY-minY` `

` `jj = (j-1)*(c-1)/(scaleC*c-1) + 1 ii = (i-1)*(r-1)/(scaleR*r-1) + 1` `

` `% read a sample image inputI = imread('coins.png'); [r,c] = size(inputI); scale = [2 2]; % you could scale each dimension differently outputI = zeros(scale(1)*r,scale(2)*c, class(inputI)); for i=1:scale(1)*r for j=1:scale(2)*c % map from output image location to input image location ii = round( (i-1)*(r-1)/(scale(1)*r-1)+1 ); jj = round( (j-1)*(c-1)/(scale(2)*c-1)+1 ); % assign value outputI(i,j) = inputI(ii,jj); end end figure(1), imshow(inputI) figure(2), imshow(outputI)` `

MATLAB已经为你做了。 使用imresize ：

` `output = imresize(input,size(input)*2,'nearest');` `

` `output = imresize(input,2,'nearest');` `

` `xloc = (j * (newwidth+1)) / (x+1); yloc = (i * (newheight+1)) / (y+1);` `

• WPF：将宽度（和高度）设置为百分比值
• 为什么Firefox在调整图像大小方面如此糟糕？
• resize后的图像质量很低 - Java
• canvasdrawImage缩放
• 缩放图像以适合边界框
• 在iOS上使用CSS的iframe大小
• 计算resize的图像大小比例
• 如何从NSImage保存PNG文件（视网膜问题）
• 为什么在C ++ 11中改变了std :: vector :: resize签名？
• JavaScript的`window.resizeTo`不工作
• 使用jQuery调整表格列