如何在图像中放置边距?
How can I put margins in an image?
我有一个 18x18 像素的二值图像,我想在该图像周围放置边距以获得 20x20 像素的图像。
图像是二进制的,可以用1和0的矩阵表示。 0 像素为黑色,1 像素为白色。我需要在我拥有的图像周围放置 1 个零像素的边距。
我该怎么做?
A=ones(18,18);%// your actual image
[M,N] = size(A);
B = zeros(M+2,N+2);%// create matrix
B(2:end-1,2:end-1) = A; %// matrix with zero edge around.
这首先获取图像矩阵的大小,并创建一个具有两个附加列和行的零矩阵,之后您可以将除外边缘之外的所有内容设置为图像矩阵。
大小为 [4x6]
的非方阵示例:
B =
0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 0
0 1 1 1 1 1 1 0
0 1 1 1 1 1 1 0
0 1 1 1 1 1 1 0
0 0 0 0 0 0 0 0
首先制作一个由 20 x 20 个零组成的矩阵,Zimg
,然后将您的图像矩阵插入到由零组成的矩阵中:
Zimg(2:end-1,2:end-1)=img;
图像处理工具箱中的 padarray
函数可用于此目的:
B=padarray(A,[1,1])
让我们开始吧:
%// Data:
A = magic(3); %// example original image (matrix)
N = 1; %// margin size
%// Add margins:
A(end+N, end+N) = 0; %// "missing" values are implicitly filled with 0
A = A(end:-1:1, end:-1:1); %// now flip the image up-down and left-right ...
A(end+N, end+N) = 0; %// ... do the same for the other half ...
A = A(end:-1:1, end:-1:1); %// ... and flip back
我有一个 18x18 像素的二值图像,我想在该图像周围放置边距以获得 20x20 像素的图像。
图像是二进制的,可以用1和0的矩阵表示。 0 像素为黑色,1 像素为白色。我需要在我拥有的图像周围放置 1 个零像素的边距。
我该怎么做?
A=ones(18,18);%// your actual image
[M,N] = size(A);
B = zeros(M+2,N+2);%// create matrix
B(2:end-1,2:end-1) = A; %// matrix with zero edge around.
这首先获取图像矩阵的大小,并创建一个具有两个附加列和行的零矩阵,之后您可以将除外边缘之外的所有内容设置为图像矩阵。
大小为 [4x6]
的非方阵示例:
B =
0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 0
0 1 1 1 1 1 1 0
0 1 1 1 1 1 1 0
0 1 1 1 1 1 1 0
0 0 0 0 0 0 0 0
首先制作一个由 20 x 20 个零组成的矩阵,Zimg
,然后将您的图像矩阵插入到由零组成的矩阵中:
Zimg(2:end-1,2:end-1)=img;
图像处理工具箱中的 padarray
函数可用于此目的:
B=padarray(A,[1,1])
让我们开始吧:
%// Data:
A = magic(3); %// example original image (matrix)
N = 1; %// margin size
%// Add margins:
A(end+N, end+N) = 0; %// "missing" values are implicitly filled with 0
A = A(end:-1:1, end:-1:1); %// now flip the image up-down and left-right ...
A(end+N, end+N) = 0; %// ... do the same for the other half ...
A = A(end:-1:1, end:-1:1); %// ... and flip back