MATLAB: Drawing a line over a black and white image

前端 未结 5 1884
生来不讨喜
生来不讨喜 2020-11-30 10:01

What is the best way to draw a line over a black and white (binary) image in MATLAB, provided the start and end coordinates are known?

Please note, I am not trying t

5条回答
  •  不知归路
    2020-11-30 10:52

    It actually is just a modification on plesiv's answer. I'm drawing thousands of lines over an image and I need to increase the performance. The most improvement made by omitting interp1 calls and using integer variables made it slightly faster. It performs about 18% faster on my PC comparing to plesiv's code.

    function img = drawLine(img, x1, y1, x2, y2)
    x1=int16(x1); x2=int16(x2); y1=int16(y1); y2=int16(y2);
    % distances according to both axes
    xn = double(x2-x1);
    yn = double(y2-y1);
    
    % interpolate against axis with greater distance between points;
    % this guarantees statement in the under the first point!
    if (abs(xn) > abs(yn))
        xc = x1 : sign(xn) : x2;
        if yn==0
            yc = y1+zeros(1, abs(xn)+1, 'int16');
        else
        yc = int16(double(y1):abs(yn/xn)*sign(yn):double(y2));
        end
    else
        yc = y1 : sign(yn) : y2;
        if xn==0
            xc = x1+zeros(1, abs(yn)+1, 'int16');
        else
        xc = int16(double(x1):abs(xn/yn)*sign(xn):double(x2));
        end
    end
    
    % 2-D indexes of line are saved in (xc, yc), and
    % 1-D indexes are calculated here:
    ind = sub2ind(size(img), yc, xc);
    
    % draw line on the image (change value of '255' to one that you need)
    img(ind) = 255;
    end
    

提交回复
热议问题