Is there an efficient way to pad a matrix with zeros on all sides?

和自甴很熟 提交于 2019-12-12 13:19:47

问题


I'm performing texture synthesis on images using the Efros and Leung Algorithm. My goal is to grow the size of my current textured image and, to do it, I'd like to pad the current image matrix with zeros on all sides.

My current plan given an original image matrix of size MxN and a desired growth size of P:
(1) Create a target matrix of size (M+2P)x(N+2P)
(2) Set the value of target(i+P,j+P) = original(i,j)
(3) Run Efros and Leung

Is there a way I can eliminate (1) and (2) and just operate on the original image to pad it in all directions with P zeros?


回答1:


If you have access to the Image Processing Toolbox, you can use the function PADARRAY:

imgPadded = padarray(img, [p p], 0, 'both');

Otherwise you can simply use matrix indexing:

sz = size(img);
imgPadded = zeros([sz(1:2)+2*p size(img,3)], class(img));
imgPadded((1:sz(1))+p, (1:sz(2))+p, :) = img;

This should work for both grayscale and RGB images.




回答2:


>> y = [zeros(P,N+2*P) ; [zeros(M,P), x, zeros(M,P)] ; zeros(P,N+2*P)];

where x is the original image matrix and y is the output should work. If the matrix has 3 planes, adjust to:

>> y = [zeros(P,N+2*P,3) ; [zeros(M,P,3), x, zeros(M,P,3)] ; zeros(P,N+2*P,3)];



回答3:


Use padarray:

y = padarray(x, [P P]);


来源:https://stackoverflow.com/questions/8287289/is-there-an-efficient-way-to-pad-a-matrix-with-zeros-on-all-sides

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!