双线性插值matlab代码
时间: 2023-08-01 16:15:13 浏览: 83
以下是双线性插值的 MATLAB 代码示例:
```matlab
function [out] = bilinear_interpolation(im, x, y)
% im: input image
% (x,y): pixel position of the output image
% Get the size of the input image
[height, width] = size(im);
% Calculate the four nearest pixels
x1 = floor(x);
x2 = x1 + 1;
y1 = floor(y);
y2 = y1 + 1;
% Check if the pixel is out of the boundaries of the input image
if x2 > width
x2 = width;
end
if y2 > height
y2 = height;
end
% Calculate the weights for each pixel
w1 = (x2 - x) * (y2 - y);
w2 = (x - x1) * (y2 - y);
w3 = (x2 - x) * (y - y1);
w4 = (x - x1) * (y - y1);
% Calculate the interpolated pixel value
out = w1 * im(y1, x1) + w2 * im(y1, x2) + w3 * im(y2, x1) + w4 * im(y2, x2);
end
```
该函数通过输入图像 `im` 和输出图像中的像素位置 `(x, y)`,计算出双线性插值后的像素值 `out`。其中,四个最近的像素位置 `(x1, y1)`、`(x2, y1)`、`(x1, y2)`、`(x2, y2)` 可以通过向下取整计算出来。然后计算每个像素的权重 `w1`、`w2`、`w3`、`w4`,最后通过加权平均计算出输出像素值 `out`。
阅读全文