Matlab: how to avoid ellipses overlapping in image?

前端 未结 3 631
北恋
北恋 2020-12-21 22:35

I\'ve been using a function file [ret]=drawellipse(x,y,a,b,angle,steps,color,img). Calling the function through a script file to draw random ellipses in image.

3条回答
  •  没有蜡笔的小新
    2020-12-21 23:19

    The solution proposed by @arne.b (the first one) is a good way to rasterize non-overlapping ellipses.

    Let me illustrate that idea with an example. I will be extending my previous answer:

    %# color image
    I = imread('pears.png');
    sz = size(I);
    
    %# parameters of ellipses
    num = 7;
    h = zeros(1,num);
    clr = lines(num);             %# color of each ellipse
    x = rand(num,1) .* sz(2);     %# center x-coords
    y = rand(num,1) .* sz(1);     %# center y-coords
    a = rand(num,1) .* 200;       %# major axis length
    b = rand(num,1) .* 200;       %# minor axis length
    angle = rand(num,1) .* 360;   %# angle of rotation
    
    %# label image, used to hold rasterized ellipses
    BW = zeros(sz(1),sz(2));
    
    %# randomly place ellipses one-at-a-time, skip if overlaps previous ones
    figure, imshow(I)
    axis on, hold on
    for i=1:num
        %# ellipse we would like to draw directly on image matrix
        [ex,ey] = calculateEllipse(x(i),y(i), a(i),b(i), angle(i), 100);
    
        %# lets plot the ellipse (overlayed)
        h(i) = plot(ex,ey, 'LineWidth',2, 'Color',clr(i,:));
    
        %# create mask for image pixels inside the ellipse polygon
        mask = poly2mask(ex,ey,sz(1),sz(2));
    
        %# get the perimter of this mask
        mask = bwperim(mask,8);
    
        %# skip if there is an existing overlapping ellipse
        if any( BW(mask)~=0 ), continue, end
    
        %# use the mask to place the ellipse in the label image
        BW(mask) = i;
    end
    hold off
    legend(h, cellstr(num2str((1:num)','Line%d')), 'Location','BestOutside')    %'
    
    %# set pixels corresponding to ellipses using specified colors
    clr = im2uint8(clr);
    II = I;
    for i=1:num
        BW_ind = bsxfun(@plus, find(BW==i), prod(sz(1:2)).*(0:2));
        II(BW_ind) = repmat(clr(i,:), [size(BW_ind,1) 1]);
    end
    figure, imshow(II, 'InitialMagnification',100, 'Border','tight')
    

    all_overlayed_ellipses rasterized_nonoverlapping_ellipses

    Note how the overlap test is performed in the order the ellipses are added, thus after Line1 (blue) and Line2 (green) are drawn, Line3 (red) will be skipped because it overlaps one of the previous ones, and so on for the rest...

提交回复
热议问题