使用渐变创建圆

时间:2017-02-19 16:09:05

标签: matlab

在另一个帖子中,我发现这段代码可以创建一个包含渐变的圆圈(plot circle with gradient gray scale color in matlab):

N = 200; %// this decides the size of image
[X,Y] = meshgrid(-1:1/N:1, -1:1/N:1) ;
nrm = sqrt(X.^2 + Y.^2);
out = uint8(255*(nrm/min(nrm(:,1)))); %// output image
padsize = 50; %// decides the boundary width
out = padarray(out,[padsize padsize],0);
figure, imshow(out) %// show image

现在我想用一个递减值的固定向量替换该渐变,这样每个半径都有它自己的值。

提前感谢您对此的任何帮助

2 个答案:

答案 0 :(得分:1)

这是一种用向量中的值替换元素的优雅方法:

假设你的矢量是:V = 283:-1:0 我使用降序值进行演示 值283是sqrt(2)*N(应该是边界方块中的最大半径)。

原始帖子的代码差异:

  1. out除以max(out(:)) - 将范围设置为[0, 1]
  2. 乘以V(减1)的长度 - 将范围设置为[0, length(V)-1]
  3. 使用round代替uint8(将uint8钳位值转换为255)。
  4. 使用向量V作为查找表 - 用值V替换out的每个元素代替值。
  5. 以下是代码:

    N = 200; %// this decides the size of image
    
    %V = round(sqrt(2)*N):-1:0;
    
    %Assume this is your vector.
    V = 283:-1:0;
    
    [X,Y] = meshgrid(-1:1/N:1, -1:1/N:1) ;
    nrm = sqrt(X.^2 + Y.^2);
    %out = uint8(255*(nrm/min(nrm(:,1)))); %// output image
    
    %1. Divide by max(out(:)) - set the range of out to [0, 1].
    %2. Multiply by length of V (minus 1) - set the range of out to [0, length(V)-1].
    %3. Use round instead of uint8 (converting to uint8 clamps value to 255).
    out = nrm/min(nrm(:,1));
    out = round(out/max(out(:)) * (length(V)-1));
    
    %4. Use vector V as a Look Up Table - replace each elements of out with value of V in place of the value.
    out = V(out+1);
    
    padsize = 50; %// decides the boundary width
    out = padarray(out,[padsize padsize],0);
    %figure, imshow(out) %// show image
    figure, imagesc(out);impixelinfo;colormap hsv %// use imagesc for emphasis values.
    

    如您所见,值来自向量V

    enter image description here

答案 1 :(得分:0)

尝试

R = sqrt(X.^2+Y.^2);
out = uint8(255*R);
padsize = 50; %// decides the bounary width
out = padarray(out,[padsize padsize],0);
figure, imshow(out) %// show image