通过用1s填充边框来扩展图像的大小

时间:2015-07-07 13:26:38

标签: matlab image-processing

我想用MATLAB扩展我的图像大小。例如,我有397x450的图像我希望将其放入600x600,我将原始图像放在中间,但所有新元素必须为1,即397x450元素将保持与原始图像相同,并将放置在输出图像的中间,600x600图像中的其余元素将被1

在MATLAB中有一种有效的方法吗?

2 个答案:

答案 0 :(得分:2)

如果要扩展图像以使原始内容位于中间,可以计算输出图像的中间值,该图像初始化为全1,然后确保放置图像以使其跨越宽度和高度原来的。如果您输入的图像甚至在尺寸上会变得很混乱......但假设您有奇数尺寸,请执行以下操作:

rows_out = 600; cols_out = 600;
out = ones(rows_out, cols_out, size(im,3));

rows_in = size(im,1); cols_in = size(im,2);
rows_half = floor(rows_in/2); cols_half = floor(cols_in/2);

out_half_rows = floor(rows_out/2); out_half_cols = floor(cols_out/2);

out(out_half_rows-rows_half : out_half_rows+rows_half, ...
    out_half_cols-cols_half : out_half_cols+cols_half, :) = im;

作为附加检查,您可以通过检查除以2的余数来检查图像是否具有偶数行或列,如果有提醒,我们可以删除最后一行和/或列,例如:< / p>

rows_in = size(im,1) - (mod(size(im,1),2) + 1);
cols_in = size(im,2) - (mod(size(im,2),2) + 1); 
im = im(1:rows_in, 1:cols_in, :);

请注意,上面的代码将删除最后两行和两列,因为它是奇数。

这是一个在600 x 600白色背景上使用256 x 256黑色正方形的示例:

out = ones(600,600);
im = zeros(256,256);

使用上述检查确保奇怪的图像尺寸,我们得到:

enter image description here

答案 1 :(得分:1)

你可以做到

result = zeros(600);
result(102:498,75:524) = image;