What is an simple way to compute the overlap between an image and a polygon?

前端 未结 6 1252
清酒与你
清酒与你 2020-12-16 05:03

I have a closed non-self-intersecting polygon. Its vertices are saved in two vectors X, and Y. Finally the values of X and Y are bound between 0 and 22.

I\'d like t

6条回答
  •  我在风中等你
    2020-12-16 05:32

    First I define a low resolution circle for this example

    X=11+cos(linspace(0,2*pi,10))*5;
    Y=11+sin(linspace(0,2.01*pi,10))*5;
    

    Like your example it fits with in a grid of ~22 units. Then, following your lead, we declare a meshgrid and check if points are in the polygon.

    stepSize=0.1;
    [a b] = meshgrid(1:stepSize:22);
    inPoly1 = inpolygon(a,b,X,Y);
    

    Only difference is that where your original solution took steps of one, this grid can take smaller steps. And finally, to include anything within the "edges" of the squares

    inPolyFull=unique( round([a(inPoly1) b(inPoly1)]) ,'rows');
    

    The round simply takes our high resolution grid and rounds the points appropriately to their nearest low resolution equivalents. We then remove all of the duplicates in a vector style or pair-wise fashion by calling unique with the 'rows' qualifier. And that's it

    To view the result,

    [aOrig bOrig] = meshgrid(1:22);
    imagesc(1:stepSize:22,1:stepSize:22,inPoly1); hold on;
    plot(X,Y,'y');
    plot(aOrig,bOrig,'k.');
    plot(inPolyFull(:,1),inPolyFull(:,2),'w.'); hold off;
    

    Example polygon

    Changing the stepSize has the expected effect of improving the result at the cost of speed and memory.

    If you need the result to be in the same format as the inPoly2 in your example, you can use

    inPoly2=zeros(22);
    inPoly2(inPolyFull(:,1),inPolyFull(:,2))=1
    

    Hope that helps. I can think of some other ways to go about it, but this seems like the most straightforward.

提交回复
热议问题