MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   MATLAB中的最近邻插值算法 (https://www.labfans.com/bbs/showthread.php?t=22822)

poster 2019-12-10 16:49

MATLAB中的最近邻插值算法
 
我正在尝试编写自己的函数,以使用最近邻插值算法按比例放大输入图像。不好的部分是我能够看到它是如何工作的,但是找不到算法本身。我将不胜感激。

这是我尝试将输入图像放大2倍的方法:

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 这是[URL="https://stackoverflow.com/users/5987/mark-ransom"]Mark[/URL]建议后的输出[IMG]https://i.stack.imgur.com/KnNpF.png[/IMG]


回答:
[URL="http://www.mathworks.com/help/images/ref/imresize.html"]imresize[/URL] ,我在[URL="https://www.mathworks.com/products/image.html"]MATLAB Image Processing Toolbox[/URL]中浏览了[URL="http://www.mathworks.com/help/images/ref/imresize.html"]imresize[/URL]函数的代码,以创建仅用于图像的最近邻居插值的简化版本。这是将其应用于您的问题的方式:

%# 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,:); 另一个选择是使用内置的[URL="http://www.mathworks.com/help/matlab/ref/interp2.html"]interp2[/URL]函数,尽管您在一个评论中提到不想使用内置的函数。

[B]编辑:解释[/B]

如果有人感兴趣,我想我会解释一下上面的解决方案是如何工作的...

newSize = max(floor(scale.*oldSize(1:2)),1); 首先,要获得新的行和列大小,将旧的行和列大小乘以比例因子。该结果四舍五入为带有[URL="http://www.mathworks.com/help/matlab/ref/floor.html"]floor[/URL]的最接近的整数。如果比例因子小于1,您可能会遇到一个奇怪的情况,即大小值之一为0,这就是为什么对[URL="http://www.mathworks.com/help/matlab/ref/max.html"]max[/URL]的调用会用1替换小于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)); 接下来,为行和列都计算一组新的索引。首先,计算上采样图像的一组索引: 1:newSize(...) 。每个图像像素都被视为具有给定的宽度,因此像素1的范围是0到1,像素2的范围是1到2,依此类推。因此,像素的“坐标”被视为中心,这就是为什么0.5从索引中减去。然后,将这些坐标除以比例因子,以得到原始图像的一组像素中心坐标,然后将它们添加0.5,然后四舍五入以获得一组原始图像的整数索引。对[URL="http://www.mathworks.com/help/matlab/ref/min.html"]min[/URL]的调用确保这些索引均不大于原始图像大小oldSize(...) 。

outputImage = inputImage(rowIndex,colIndex,:); 最后,只需简单地索引原始图像即可创建新的上采样图像。



[url=https://stackoverflow.com/questions/1550878]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 23:21

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.