![](/img/trans.png)
[英]How to create a 3D matrix in MATLAB by rotating 2D matrix around its center column or center row?
[英]How to create a 2D image by rotating 1D vector of numbers around its center element?
我有数字的一维向量,代表圆形对称对象的中心切割。 向量本身围绕其中心元素对称。 我想在MATLAB中通过围绕其中心元素旋转1D向量来创建原始对象的2D图像。
我尝试了以下代码(使用虚拟的原始数字矢量),但是从生成的2D图像中获得的中心切口与原始1D矢量不匹配,如果您运行该代码可以看到。 我将不胜感激!
close all; clc
my1D_vector=[ zeros(1,20) ones(1,15) zeros(1,20)]; % original vector
len=length(my1D_vector);
img=zeros(len, len);
thetaVec=0:0.1:179.9; % angles through which to rotate the original vector
numRotations=length(thetaVec);
% the coordinates of the original vector and the generated 2D image:
x=(1:len)-(floor(len/2)+1);
y=x;
[X,Y]=meshgrid(x,y);
for ind_rotations=1:numRotations
theta=pi/180*thetaVec(ind_rotations);
t_theta=X.*cos(theta)+Y.*sin(theta);
cutContrib=interp1(x , my1D_vector , t_theta(:),'linear');
img=img+reshape(cutContrib,len,len);
end
img=img/numRotations;
figure('name','original vector');plot(x,my1D_vector,'b.-')
figure('name','generated 2D image'); imagesc(x,y,img); colormap(gray) ;
figure('name','comparison between the original vector and a center cut from the generated 2D image');
plot(x,my1D_vector,'b.-')
hold on
plot(x,img(find(x==0),:),'m.-')
legend('original 1D vector','a center cut from the generated 2D image')
我没有遵循您的代码,但是如何处理:
V = [ zeros(1,20) ones(1,15) zeros(1,20)]; % Any symmetrical vector
n = floor(numel(V)/2);
r = [n:-1:0, 1:n]; % A vector of distance (measured in pixels) from the center of vector V to each element of V
% Now find the distance of each element of a square 2D matrix from it's centre. @(x,y)(sqrt(x.^2+y.^2)) is just the Euclidean distance function.
ri = bsxfun(@(x,y)(sqrt(x.^2+y.^2)),r,r');
% Now use those distance matrices to interpole V
img = interp1(r(1:n+1),V(1:n+1),ri);
% The corners will contain NaN because they are further than any point we had data for so we get rid of the NaNs
img(isnan(img)) = 0; % or instead of zero, whatever you want your background colour to be
因此,我不是在角度上进行插值,而是在半径上进行插值。 So r
表示一维中与V
的每个元素的中心的距离的向量。 ri
然后代表二维中心距。这些是我们要插值的值。 然后我只使用r
和V
一半,因为它们是对称的。
之后,您可能希望将所有NaN
都设置为0
,因为无法插入角,因为它们的半径大于V
最远点的半径。
使用您的绘图代码,我得到
和
蓝色和品红色曲线完全重叠。
想象一下,向量V
只是1
× 5
向量。 然后,此图显示r
和ri
是:
我没有在图表上标记它,但r'
将是中间一列。 现在从代码中
ri = bsxfun(@(x,y)(sqrt(x.^2+y.^2)),r,r');
并根据图r = [2,1,0,1,2]
所以现在对于每个像素,我们都具有距中心的欧式距离,因此像素(1,1)将为sqrt(r(1).^2+r(1).^2)
如图所示,是sqrt(2.^2+2.^2)
sqrt(r(1).^2+r(1).^2)
,是sqrt(8)
。
另外,您会注意到我“变灰”了四角像素。 这些像素比我们拥有数据的任何点都离中心更远,因为我们数据的最大半径(与中心的距离)为2
但sqrt(8) > sqrt(5) > 2
因此您无法对这些数据进行插值,您将不得不推断以获取它们的价值。 对于这些点, interp1
返回NaN
。
为什么插值有效? 将每个像素的位置视为指向像素中心 。 现在在此图中,红色圆圈是当您旋转外部元素(即r==2
)而绿色正在进一步旋转元素1(即r==1
)时发生的情况。 您将看到,当我们旋转它们时,获得sqrt(2)
距离(蓝色箭头)的像素位于这两个半径之间,因此我们必须对这两个像素之间的距离进行插值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.